Python中有_tuple的用法吗?
我阅读了今天的官方文档,在Python中有_tuple的用法吗?,python,namedtuple,python-internals,Python,Namedtuple,Python Internals,我阅读了今天的官方文档,在\uuu new\uu方法中找到了\u tuple。我没有找到\元组的定义位置 您可以尝试在Python中运行下面的代码,它不会引发任何错误 >>> Point = namedtuple('Point', ['x', 'y'], verbose=True) class Point(tuple): 'Point(x, y)' __slots__ = () _fields = ('x', 'y') def __new_
\uuu new\uu
方法中找到了\u 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
成为一个受保护的值吗?我说的对吗?来自泛型(您可以通过打印点来查看为这个特定名称的对偶生成的源代码。\ u source
):
因此\u tuple
这里只是内置tuple
类型的别名:
In [1]: from builtins import tuple as _tuple
In [2]: tuple is _tuple
Out[2]: True
Python2.6.0中添加了collections.namedtuple
。这是\uuuu new\uuuu
方法的初始源代码:
def __new__(cls, %(argtxt)s):
return tuple.__new__(cls, (%(argtxt)s)) \n
问题是,源代码是字符串。他们随后使用%locals()
对其进行格式化。如果tuple
列在argtxt
中,则tuple.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu新
将调用tuple
字段所包含的方法。相反,\u元组
按预期工作,因为namedtuple
不允许字段名以\u
开头
该错误在Python 2.6.3版本中已修复(请参阅-collections.namedtuple()未使用以下字段名:cls、self、tuple、itemgetter和property)。+1这是一个正确答案。使用了_tuple(),用户可以创建类似于Args=namedtuple(“Args”、[“tuple”、“dict”])
。支持此行为很重要,因为字段名可能不受用户控制(即CSV文件中的标题)。
def __new__(cls, %(argtxt)s):
return tuple.__new__(cls, (%(argtxt)s)) \n