我正在使用isinstance来检查参数类型,但我找不到正则表达式模式对象的类名:
>>> import re
>>> x = re.compile('test')
>>> x.__class__.__name__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __class__
...
>>> type(x)
<type '_sre.SRE_Pattern'>
>>> isinstance(x, _sre.SRE_Pattern)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_sre' is not defined
>>>
>>>
>>> isinstance(x, '_sre.SRE_Pattern')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
>>>
有什么想法吗?
答案 0 :(得分:4)
你可以这样做:
import re
pattern_type = type(re.compile("foo"))
if isinstance(your_object, pattern_type):
print "It's a pattern object!"
惯用的方法是尝试将其用作模式对象,然后处理生成的异常(如果不是)。
答案 1 :(得分:0)
In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True
In [14]: type(type(x))
Out[14]: <type 'type'>
我认为它与类型/对象子实体和重新模块实现有关。你可以阅读一篇好文章here。