gpt4 book ai didi

python - namedtuple — 同一定义中不同类型名称的应用

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:17 26 4
gpt4 key购买 nike

Python namedtuple 工厂函数允许它创建的子类的名称被指定两次——第一次在声明的左侧,然后作为函数的第一个参数(IPython 1.0.0 , Python 3.3.1):

In [1]: from collections import namedtuple

In [2]: TypeName = namedtuple('OtherTypeName', ['item'])

我在 docs.python.org 网站上看到的所有示例在两个位置都使用相同的名称。但是可以使用不同的名称,它们的功能也不同:

In [3]: TypeName(1)
Out[3]: OtherTypeName(item=1)

In [4]: type(TypeName)
Out[4]: builtins.type

In [5]: type(OtherTypeName)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-6616c1214742> in <module>()
----> 1 type(OtherTypeName)

NameError: name 'OtherTypeName' is not defined

In []: OtherTypeName(1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-47d6b5709a5c> in <module>()
----> 1 OtherTypeName(1)

NameError: name 'OtherTypeName' is not defined

我想知道这个功能可能有哪些应用程序。

最佳答案

您没有指定名称两次。您在调用 namedtuple 时指定一个“内部”名称,然后将生成的 namedtuple 类型分配给一个变量。

您指定作为 namedtuple 参数的那个是生成的 namedtuple 类型自己对其名称的想法——也就是说,“它称呼自己”。等号左边的东西只是一个普通的 Python 变量,您可以为其分配 namedtuple 类型。

如果你将它分配给某物,你只能使用你创建的命名元组,并且你只能通过你分配给它的名称来使用它。将“OtherTypeName”作为“名称”传递并不会神奇地创建一个名为 OtherTypeName 的变量,这就是当您尝试使用名称 OtherTypeName 时会收到 NameError 的原因。传递给 namedtuple 的名称(在您的情况下为“OtherTypeName”)的唯一实际用途是显示结果值。

显然,在很多情况下,让您用来引用 namedtuple 的变量与它自己的内部名称相同是件好事;它使事情不那么困惑。但是你可以有多个变量指向同一个命名元组:

NameOne = namedtuple('OtherTypeName', ['item'])
NameTwo = NameOne

. . .或者没有直接指向它的变量,只能通过一些容器访问它:

x = []
x.append(namedtuple('OtherTypeName', ['item']))
x[0] # this is your namedtuple

与其说它有特殊的“应用程序”,不如说它的行为本身并不特殊:namedtuple 是一个与其他任何对象一样的对象,创建对象与创建引用变量不同

关于python - namedtuple — 同一定义中不同类型名称的应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18432203/

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