Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中有_tuple的用法吗?_Python_Namedtuple_Python Internals - Fatal编程技术网

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