在 8.3. collections — Container datatypes — Python 3.6.4rc1 documentation ,
它指定了 namedtuple
的 5 个方法。
namedtuple_methods = {'_fields', '_make', '_replace', '_asdict', '_source'}
但是,这些方法无法通过 dir
方法获取
from collections import namedtuple
set(dir(namedtuple)) & namedtuple_methods
In [64]: set(dir(namedtuple)) & namedtuple_methods
Out[64]: set()
它们没有交集。
有趣的是,一个特定的namedtuple
列出了方法
Book = namedtuple('Book', 'name, author')
In [70]: set(dir(Book)) & namedtuple_methods
Out[70]: {'_asdict', '_fields', '_make', '_replace', '_source'}
背后的机制是什么?
最佳答案
namedtuple
是一个工厂函数(从字面上看,源代码中有一个以 def namedtuple(
) 开头的函数),它本身不是一个类(它创建tuple
的子类,但它不是 tuple
或 namedtuple
)。普通的 def
-ed 函数不会'没有任何这样的特殊方法。
关于python - dir() 未列出的namedtuple 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47812380/