Define a new type Person
using namedtuple
like this:
Person = namedtuple('Person', ['age', 'height', 'name'])
The second argument is the list of attributes that the tuple will have. You can list these attributes also as either space or comma separated string:
Person = namedtuple('Person', 'age, height, name')
or
Person = namedtuple('Person', 'age height name')
Once defined, a named tuple can be instantiated by calling the object with the necessary parameters, e.g.:
dave = Person(30, 178, 'Dave')
Named arguments can also be used:
jack = Person(age=30, height=178, name='Jack S.')
Now you can access the attributes of the namedtuple:
print(jack.age) # 30
print(jack.name) # 'Jack S.'
The first argument to the namedtuple constructor (in our example 'Person'
) is the typename
. It is typical to use the same word for the constructor and the typename, but they can be different:
Human = namedtuple('Person', 'age, height, name')
dave = Human(30, 178, 'Dave')
print(dave) # yields: Person(age=30, height=178, name='Dave')