python – 在namedtuple中使用’_’作为typename做了什么特别的事吗?

我正在查看在namedtuple中使用_作为typename的代码.我想知道这是什么目的.

example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'])

为什么不使用String?

解决方法:

这是一个有点奇怪的例子.重点是为类及其属性提供有意义的名称.诸如__repr__和类docstring之类的一些功能从有意义的名称中获得了大部分好处.

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')
上一篇:Python 2.6字典构建器表示法


下一篇:在Python中,元组比较是如何工作的?