Python 未按dir()列出的namedtuple的方法
在中,Python 未按dir()列出的namedtuple的方法,python,python-3.x,namedtuple,Python,Python 3.x,Namedtuple,在中, 它指定了5种namedtuple方法 namedtuple_methods = {'_fields', '_make', '_replace', '_asdict', '_source'} 然而,这些方法不能通过dir方法获得 from collections import namedtuple set(dir(namedtuple)) & namedtuple_methods In [64]: set(dir(namedtuple)) & namedtuple_met
它指定了5种
namedtuple
方法
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
).Plaindef
-ed函数不会有任何这样的特殊方法