python collections.namedtuple() 的困惑
文档中提到,任何有效的Python标识符都可以作为字段名,除了那些以下划线开头的,这个没问题。
如果rename
参数设置为真,它会把无效的字段名替换成有效的字段名。但是在文档中的例子里,它把字段名替换成了_1
或者_3
,这又是怎么回事呢?这些名字都是以下划线开头的啊!
文档还说:
如果verbose为真,类定义会在构建之前打印出来。
这到底是什么意思呢?
1 个回答
4
你不能在名字开头使用下划线的原因是,这样可能会和类里提供的方法名字冲突(比如 _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'>
这样你就可以查看你的类到底生成了什么。