gpt4 book ai didi

python - namedtuple 的第一个参数是做什么用的?

转载 作者:太空狗 更新时间:2023-10-29 17:31:59 27 4
gpt4 key购买 nike

我们像这样使用 namedtuple:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p=Point(1,2)
>>> p.x
1

我发现 namedtuple 的第一个参数似乎没用,因为:

首先,我们不能使用它(例如创建一个实例):

>>> from collections import namedtuple
>>> P = namedtuple('Point', ['x', 'y'])
>>> p = Point(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Point' is not defined

其次,它似乎没有约束(例如,我们不必使其唯一):

>>> P1 = namedtuple('Point', ['x', 'y'])
>>> P2 = namedtuple('Point', ['x', 'y', 'z'])
>>> p1 = P1(1,2)
>>> p2 = P2(1,2,3)
>>> p1
Point(x=1, y=2)
>>> p2
Point(x=1, y=2, z=3)

我没有从 manual 中找到解释或通过谷歌搜索。有个相关问题here , 但它没有回答为什么 namedtuple 需要第一个参数以及如何使用它或何时需要它。

最佳答案

它设置生成类的名称:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point
<class '__main__.Point'>
>>> Point = namedtuple('Foobar', ['x', 'y'])
>>> Point
<class '__main__.Foobar'>

全局变量中的Point 名称只是对生成类的引用,类本身 需要有一个名称。不能从分配对象的变量中获取名称,因为类是首先生成的,只有然后在单独的步骤中分配(在namedtuple之后() 调用返回)。

它不需要是唯一的,就像使用 class 时类名不需要是唯一的一样:

>>> class Foo(object):
... pass
...
>>> Bar = Foo
>>> class Foo(object):
... pass
...
>>> Bar
<class '__main__.Foo'>
>>> Foo
<class '__main__.Foo'>

您通常可以通过使每个模块的名称唯一来避免这种情况,但您必须这样做。

名称用于调试目的;在回溯和 repr() 输出中显示的名称可帮助您确定使用的是哪个类。

对于 Python,生成的类是否重用名称​​并不重要。它作用于 pickle 模块;如果您需要能够 pickle 命名的元组类实例,请确保选择一个与全局匹配的名称,pickle 稍后可以通过该名称再次加载它。但是,如果重复使用某个名称对您来说有意义,或者不会积极阻碍您的代码开发或调试任务,那么请务必重复使用该名称或选择您喜欢的任何名称。

关于python - namedtuple 的第一个参数是做什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30526115/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com