如何在Python中继承MatchObject?

时间:2011-01-29 05:32:15

标签: python

我一直在使用正则表达式,并试图继承从re.search返回的MatchObject。

我没有幸运能够访问MatchObject类。

我假设输入代码,此对象的实际类型不称为“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 个答案:

答案 0 :(得分: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)来访问对象的类型。

答案 1 :(得分:0)

可通过_sre._SRE_Match访问该类。不要问我为什么。