我看了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/