gpt4 book ai didi

python - 当我在 python 中对匹配对象执行 dir() 时,为什么没有列出 re 属性?

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:35 25 4
gpt4 key购买 nike

这是一些示例 Python 代码:

import re
some_regex = re.compile(r"\s+1\s+")
result = some_regex.search(" 1 ")
dir(result)

我使用 Python 2.6.1 得到以下结果:

 ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start']

然而 result.re 存在(来自解释器):

>>> result.re
<_sre.SRE_Pattern object at 0x10041bc90>

在使用dir() 函数时,如何不列出属性?

此页面确认了 re 属性的存在:

http://docs.python.org/library/re.html#re.MatchObject.re

现在我明白了,如果有人试图访问未通过 dir() 列出的属性,则会调用 __getattr__,但我没有看到 __getattr__ 也列为对象的属性之一,所以我摸不着头脑。

更新

这里是 Python 2.6.1 文档中 matchobject.re 存在的证明: http://docs.python.org/release/2.6.1/library/re.html#re.MatchObject.re

最佳答案

你看到这种行为是因为该类是用 C 实现的,就像 dir() 对自定义 __getattr__() 不可靠一样,它也是当 C 代码定义 getattr 函数时不可靠。

这是 SRE_Match getattr 函数的 Python 2.6 C 代码的链接:

http://hg.python.org/cpython/file/f130ce67387d/Modules/_sre.c#l3565

请注意,match_methods 数组中定义的方法具有 Python 实现,并且在 dir() 输出中可见,但由 ifmatch_getattr() 函数中是不可见的。

在 Python 2.6 中,它看起来包含以下属性:lastindex、lastgroup、string、regs、re、pos 和 endpos。

这里是一些略有不同的 Python 2.7 代码的链接。这里没有为SRE_Match实现getattr函数,所有方法和属性都可以在match_methodsmatch_membersmatch_getset数组中找到,一切都在 dir() 中可见。

http://hg.python.org/cpython/file/60a7b704de5c/Modules/_sre.c#l3612

关于python - 当我在 python 中对匹配对象执行 dir() 时,为什么没有列出 re 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11020636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com