In [1]:
import collections
Person = collections.namedtuple('Person', 'name age')
bob = Person(name='Bob', age=30)
print('\nRepresentation', bob)
In [2]:
jane = Person(name='Jane', age=29)
print('\nField by name:', jane.name)
In [3]:
print('\nField by index')
for p in [bob, jane]:
print('{} is {} years old'.format(*p))
In [7]:
import collections
try:
collections.namedtuple('Person', 'name class age')
except ValueError as err:
print(err)
In [8]:
try:
collections.namedtuple('Person', 'name age age')
except ValueError as err:
print(err)
In [9]:
import collections
with_class = collections.namedtuple(
'Person', 'name class age',
rename=True)
print(with_class._fields)
two_ages = collections.namedtuple(
'Person', 'name age age',
rename=True)
print(two_ages._fields)