documentation说任何 python 有效标识符都可以是 field_name,除了那些以下划线开头的,这很好。
如果 rename
参数为真,它会用有效的字段名替换无效的字段名,但在此处指定的示例中,它会用 _1
或 _3 替换它
,怎么样?这些以下划线开头!
文档还说:
If verbose is true, the class definition is printed just before being built
这到底是什么意思?
最佳答案
不能在名称开头使用下划线的原因是这些可能会与类提供的方法名称冲突(例如 _replace
)。
因为 只是 数字不是有效的 Python 名称,任何作为属性无效的名称(因此不是有效的 Python 标识符或以下划线开头的名称)将被替换为下划线 + 位置编号。这意味着这些生成的名称不能与有效名称冲突,也不能与类型上提供的方法冲突。
这与您可以选择的名称并不矛盾;鉴于限制,它实际上是完美的后备方案。此外,这样生成的名字很容易推导出来;这些值的属性与它们在元组中的索引直接相关。
至于将 verbose
设置为 True
,它按照锡盒上的说明进行操作。生成的namedtuple
类的源代码打印到sys.stdout
:
>>> from collections import namedtuple
>>> namedtuple('foo', 'bar baz', verbose=True)
class foo(tuple):
'foo(bar, baz)'
__slots__ = ()
_fields = ('bar', 'baz')
def __new__(_cls, bar, baz):
'Create new instance of foo(bar, baz)'
return _tuple.__new__(_cls, (bar, baz))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new foo object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return 'foo(bar=%r, baz=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
def _replace(_self, **kwds):
'Return a new foo object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('bar', 'baz'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
__dict__ = _property(_asdict)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
pass
bar = _property(_itemgetter(0), doc='Alias for field number 0')
baz = _property(_itemgetter(1), doc='Alias for field number 1')
<class '__main__.foo'>
这让您可以检查为您的类生成的确切内容。
关于python collections.namedtuple() 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23327263/