[英]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.