We use namedtuple
like this:
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p=Point(1,2)
>>> p.x
1
I found the first argument of namedtuple
seems useless, since:
Firstly, we can not use it (to create an instance, for example):
>>> 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
Secondly, there seems no constraint for it (for example, we don't have to make it unique):
>>> 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)
I did not find a explanation from the manual or by googling. There is a relevant question here, but it did not answer why namedtuple
need the first argument and how it can be used or when it's necessary.