2011-01-18 65 views
0

我使用isinstance檢查參數類型得到一個對象的類名,但我不能找到一個正則表達式對象的類名:不能在Python

>>> 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 
>>> 

任何想法?

+3

你有`import _sre`嗎?你對「NameError」感到驚訝嗎? – SilentGhost 2011-01-18 23:13:29

+0

@SilentGhost:`_sre`是一個內部模塊,並且不向外部透露`SRE_Pattern`。 – poke 2011-01-18 23:25:30

回答

4

你可以這樣做:

import re 

pattern_type = type(re.compile("foo")) 

if isinstance(your_object, pattern_type): 
    print "It's a pattern object!" 

的慣用方法是嘗試使用它作爲一個模式對象,然後處理所產生的異常,如果事實並非如此。

0
In : x = re.compile('test') 
In : isinstance(x, type(x)) 
Out: True 

In [14]: type(type(x)) 
Out[14]: <type 'type'> 

我認爲它涉及的類型/對象subtilities並向重新模塊implemetation。你可以閱讀一篇不錯的文章here