2011-01-29 32 views
3

我一直在玩正則表達式,並試圖從re.search返回的MatchObject的子類。如何在Python中繼承MatchObject?

我有沒有運氣獲得訪問的MatchObject類。

我假設輸入代碼herethat實際類型此對象的不叫「MatchObject」:

>>> re.search ("a", "a") 
<_sre.SRE_Match object at 0x100427a58> 

但是,我不能要使用這項服務對象:

import _sre 

dir (_sre) 
['CODESIZE', 'MAGIC', '__doc__', '__name__', '__package__', 'compile', 'copyright', 'getcodesize', 'getlower'] 

>>> dir(_sre.SRE_Match) 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
AttributeError: 'module' object has no attribute 'SRE_Match' 

什麼時我錯過了?

回答

2

這不是要發生的事:)

>>> import re 
>>> mo = re.search ("a", "a") 
>>> mo_class = type(mo) 
>>> mo_class 
<type '_sre.SRE_Match'> 
>>> class SubClass(mo_class): 
...  pass 
... 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Error when calling the metaclass bases 
    type '_sre.SRE_Match' is not an acceptable base type 

值得一提的是,你總是可以通過調用type(obj)雖然可以訪問對象的類型。

+0

這是怎麼回事?它是如何實現的?爲什麼文檔對我們講述類名?懶惰到rtfs :-) – 2015-07-17 08:03:20