无法在Python中获取对象的类名
我正在使用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
>>>
有什么想法吗?
2 个回答
0
In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True
In [14]: type(type(x))
Out[14]: <type 'type'>
我觉得这跟类型和对象的一些细微差别有关,还有re模块的实现。你可以在这里读到一篇不错的文章。
4
你可以这样做:
import re
pattern_type = type(re.compile("foo"))
if isinstance(your_object, pattern_type):
print "It's a pattern object!"
比较标准的做法是把它当作一个模式对象来使用,然后如果出现错误,就处理这个错误。