我使用isinstance检查参数类型,但找不到regex模式对象的类名:
>>> 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
>>> 有什么想法吗?
发布于 2011-01-19 07:16:27
你可以这样做:
import re
pattern_type = type(re.compile("foo"))
if isinstance(your_object, pattern_type):
print "It's a pattern object!"惯用的方法是尝试将其用作模式对象,如果不是,则处理产生的异常。
发布于 2011-01-19 07:27:24
In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True
In [14]: type(type(x))
Out[14]: <type 'type'>我认为它与类型/对象子实用程序和re模块实现有关。你可以阅读一篇很好的文章here。
https://stackoverflow.com/questions/4730121
复制相似问题