【问题标题】:python collections.namedtuple() confusionpython collections.namedtuple() 混淆
【发布时间】:2014-04-27 18:27:07
【问题描述】:

documentation 表示任何 python 有效标识符都可以是 field_name,但以下划线开头的除外,没关系。

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

文档还说:

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

这到底是什么意思?

【问题讨论】:

    标签: python namedtuple


    【解决方案1】:

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

    因为 just 数字不是有效的 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'>
    

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

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 1970-01-01
      • 2020-02-16
      • 2016-03-03
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多