5

collections.namedtuple我阅读了今天的官方文档,并_tuple__new__方法中找到了。我没有找到_tuple定义的位置。

您可以尝试在 Python 中运行以下代码,它不会引发任何错误。

>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
class Point(tuple):
    'Point(x, y)'

    __slots__ = ()

    _fields = ('x', 'y')

    def __new__(_cls, x, y):
        'Create a new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y)) # Here. Why _tuple?

更新:有什么优点

from builtins import property as _property, tuple as _tuple

这只是为了让tuple成为受保护的价值吗?我对吗?

4

1 回答 1

8

从通用源代码(您可以通过打印查看为此特定命名元组生成的源代码Point._source):

from builtins import property as _property, tuple as _tuple

所以_tuple这里只是内置tuple类型的别名:

In [1]: from builtins import tuple as _tuple

In [2]: tuple is _tuple
Out[2]: True

collections.namedtuple在 Python 2.6.0 中添加。这是该__new__方法的初始源代码:

def __new__(cls, %(argtxt)s):
    return tuple.__new__(cls, (%(argtxt)s)) \n

问题是,源代码在string中。他们后来使用% locals(). 如果tuple在 中列出argtxt,则将tuple.__new__调用该字段包含__new__的任何方法。tuple相反,_tuple因为namedtuple不允许以 . 开头的字段名称,所以按预期工作_

该错误已在 Python 2.6.3 版本中修复(请参阅更改日志- collections.namedtuple() 不适用于以下字段名称:cls、self、tuple、itemgetter 和 property)。

于 2014-08-16T06:25:59.637 回答