如何在Python中创建MatchObject的子类?

3

我一直在尝试使用正则表达式,并尝试继承从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个回答

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)来始终访问对象的类型。

发生了什么?它是如何实现的?为什么文档对类名撒谎?懒得读代码 :-) - Ciro Santilli OurBigBook.com

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

怎么做?我尝试过但没成功。 - ibonyun
在Python的更新版本中,它被称为re.Match。(它仍然不是一个可接受的基本类型。) - wizzwizz4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接