简体   繁体   English

Python:在基于C的类型MatchObject上使用isinstance

[英]Python : using isinstance on C based type MatchObject

I'm working on a function in which i would like to know if an object is an instance of re.MatchObject . 我正在研究一个函数,在该函数中我想知道某个对象是否是re.MatchObject的实例。 I tried to use isinstance but re.MatchObject is a C type and this does not work. 我尝试使用isinstance但是re.MatchObject是C类型,因此无法正常工作。

I still can do an alternative test like hasattr( ... , 'pos') or any other re.MatchObject attribute, but i don't consider it as a good solution. 我仍然可以进行替代测试,例如hasattr( ... , 'pos')或任何其他re.MatchObject属性,但我认为这不是一个好的解决方案。 Any other way ? 还有其他方法吗?

You'd need to use the proper type; 您需要使用正确的类型; the match object type is not explicitly importable, but you can use type() on an existing instance to store it: match对象类型不是显式可导入的,但是您可以在现有实例上使用type()来存储它:

import re

MatchObject = type(re.search('', ''))

then use that in isinstance() tests: 然后在isinstance()测试中使用它:

>>> MatchObject = type(re.search('', ''))
>>> isinstance(re.search('', ''), MatchObject)
True

There is nothing about C-defined Python types that prevents using isinstance() otherwise. 关于C定义的Python类型,没有什么可以防止使用isinstance()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM