我们可以像这样使用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)
我在手册或者谷歌搜索中没有找到解释。有一个相关的问题可以在这里找到,但是它没有回答为什么namedtuple
需要第一个参数以及如何使用或者何时需要。
__name__
,那么repr
会是什么样子?如果你设置ClassName = namedtuple('ClassName', ...)
,那么你可以使用eval
来重新创建一个给定的实例。 - jonrsharpe