3

文档说任何 python 有效标识符都可以是 field_name,但以下划线开头的除外,这很好。

如果rename参数为真,它将用有效的 field_names 替换无效的 field_names,但在此处指定的示例中,它用_1或替换它_3,这是怎么回事?这些以下划线开头!

该文件还说:

如果 verbose 为真,则在构建之前打印类定义

这到底是什么意思?

4

1 回答 1

4

您不能在名称开头使用下划线的原因是这些下划线可能会与类提供的方法名称(例如_replace)发生冲突。

因为只有数字不是有效的 Python 名称,所以任何作为属性无效的名称(因此不是有效的 Python 标识符或以下划线开头的名称)都将替换为下划线 + 位置编号。这意味着这些生成的名称不能与有效名称或类型上提供的方法发生冲突。

这与您可以选择的名称并不矛盾;考虑到这些限制,这实际上是完美的后备方案。此外,由此产生的名称很容易推断;这些值的属性与它们在元组中的索引直接相关。

至于设置verboseTrue,它会按照锡上所说的那样做。生成的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'>

这使您可以检查为您的课程生成的确切内容。

于 2014-04-27T18:33:14.863 回答