【发布时间】:2011-01-18 23:10:52
【问题描述】:
我正在使用 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
>>>
有什么想法吗?
【问题讨论】:
-
你做了
import _sre吗?NameError有什么让您惊讶的地方? -
@SilentGhost:
_sre是一个内部模块,不会向外部泄露SRE_Pattern。 -
@poke:如果你不导入
_sre,你不会知道的 -
@SilentGhost:它没有——现在仍然没有——一个对象不知道自己或者它会在一个外部模块中。
-
@zum:
x.__class__.__name__在 py3k 中对我来说很好用。我不确定我是否在关注你的对象知道自己收费。
标签: python class object types isinstance