namedtuple - 同一定义中不同类型名称的应用程序

时间:2013-08-25 18:21:47

标签: python namedtuple

Python namedtuple工厂函数允许它创建的子类的名称被指定两次 - 首先在声明的左侧,然后作为函数的第一个参数(IPython 1.0.0,Python 3.3) 0.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

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

1 个答案:

答案 0 :(得分:3)

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

你指定为namedtuple的参数的是得到的namedtuple类型自己对其名称的想法 - 即“它自称为什么”。等号左侧的东西只是一个普通的Python变量,你可以为其指定namedtuple类型。

如果您将其分配给某个东西,则只能使用您创建的namedtuple,并且只能通过您指定的名称使用它。将“OtherTypeName”作为“名称”传递并不会神奇地创建一个名为OtherTypeName的变量,这就是当您尝试使用名称OtherTypeName时获得NameError的原因。传递给namedtuple的名称的唯一实际用途(在您的情况下为“OtherTypeName”)用于显示结果值。

显然,在很多情况下,让你用来引用namedtuple的变量与它自己的内部名称相同是很好的。它让事情变得更加混乱。但是你可以有多个变量指向同一个namedtuple:

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

。 。 。或者没有直接指向它的变量,只能通过某个容器访问它:

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

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