对namedtuple中的typename使用'_'是否会做特别的事情?
问题描述:
我正在查看在namedtuple
中使用_
作为typename的代码。我想知道这是什么目的。对namedtuple中的typename使用'_'是否会做特别的事情?
example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'])
为什么不只是使用String
?
答
这是一个有点奇怪的,其名称为。整个观点是为班级及其属性提供有意义的名称。某些功能(如__repr__和类文档字符串)从有意义的名称中获得大部分好处。
FWIW,在namedtuple工厂包括详细选项,它可以很容易地了解工厂与它的投入做。当verbose=True
,工厂打印出的类定义它创造:
>>> from collections import namedtuple
>>> example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'], verbose=True)
class _(tuple):
'_(NameOfClass1, NameOfClass2)'
__slots__ =()
_fields = ('NameOfClass1', 'NameOfClass2')
def __new__(_cls, NameOfClass1, NameOfClass2):
'Create new instance of _(NameOfClass1, NameOfClass2)'
return _tuple.__new__(_cls, (NameOfClass1, NameOfClass2))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new _ 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 '_(NameOfClass1=%r, NameOfClass2=%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 _ object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('NameOfClass1', 'NameOfClass2'), _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)
NameOfClass1 = _property(_itemgetter(0), doc='Alias for field number 0')
NameOfClass2 = _property(_itemgetter(1), doc='Alias for field number 1')
答
只是表示生成的类的名称是不相关的。
为什么要用'“String''并不仅仅是'” _''? ;)两者都是同样有效的标识符。 – delnan
FWIW,程序员通常使用“_”作为未使用的可抛弃变量名称。 –