python - _tuple 在 Python 中有用吗?

标签 python namedtuple python-internals

我看了collections.namedtuple的官方文档今天在__new__ 方法中发现了_tuple。我没有找到 _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 成为一个 protected 值?我说得对吗?

最佳答案

来自通用 source code (您可以通过打印 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 版本中修复(参见 changelog - collections.namedtuple() 无法使用以下字段名称:cls、self、tuple、itemgetter 和 property).

关于python - _tuple 在 Python 中有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25337530/

相关文章:

python - for循环到列表理解

python - 获取列表中每 n 个项目的一大块项目

Python 3.5 - 创建填充有生成器的命名元组

python - 如何改变命名元组?

python - PyUnicode字符串和C字符串之间的字符串转换是如何工作的?

python - Python for 循环实际上是如何工作的?

python - 使用 sklearn 和 pandas 进行决策树的 ValueError?

c# - 使用命名元组作为输入参数的 API 调用

python - Python 是否优化了仅用作返回值的变量?

python - Pyhook 在按 6 次后停止捕获按键事件