python collections.namedtuple() 混淆

标签 python namedtuple

documentation说任何 python 有效标识符都可以是 field_name,除了那些以下划线开头的,这很好。

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

文档还说:

If verbose is true, the class definition is printed just before being built

这到底是什么意思?

最佳答案

不能在名称开头使用下划线的原因是这些可能会与类提供的方法名称冲突(例如 _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'>

这让您可以检查为您的类生成的确切内容。

关于python collections.namedtuple() 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23327263/

相关文章:

python - 有什么方法可以绕过 namedtuple 255 个参数限制?

python - dir() 未列出的namedtuple 方法

python - 无法修改 django rest framework base.html 文件

python - 在 python 中展开列表

python - matplotlib:在忽略缺失数据的点之间画线

python - if else 在 for 循环下工作 != but ==

python - 如何在 Django 中使用 Q.AND 限制对 ManyToMany 关系的查询

python - 并行遍历 numpy 数组并创建新结果数组的有效方法

python - 使用 namedtuples 迁移正在运行的代码