In the Collections module of the namedtuple class bit field, accessing data through attributes with namedtuple makes our code more intuitive and better maintained, the following describes the usage of the namedtuple class in Python Programming. the Collections module of Python provides a lot of useful data container types. one of the excellent products is namedtuple.
Namedtuple can be used to create a data type similar to the ancestor. in addition to being able to access data using indexes, namedtuple can be used for iteration and data access through attribute names conveniently.
In python, the traditional tuple is similar to an array and can only access each element through subscript. we also need to comment out what data each subscript represents. By using namedtuple, each element has its own name, similar to struct in C language, so that the meaning of data can be clearly understood. Of course, it is very simple and convenient to declare namedtuple.
The sample code is as follows:
from collections import namedtuple Friend=namedtuple("Friend",['name','age','email']) f1=Friend('xiaowang',33,'xiaowang@163.com')print(f1)print(f1.age)print(f1.email)f2=Friend(name='xiaozhang',email='xiaozhang@sina.com',age=30)print(f2) name,age,email=f2print(name,age,email)
Similar to tuple, its attributes are also unchangeable:
>>> big_yellow.age += 1Traceback (most recent call last): File "
", line 1, in
AttributeError: can't set attribute
It can be easily converted to OrderedDict:
>>> big_yellow._asdict()OrderedDict([('name', 'big_yellow'), ('age', 3), ('type', 'dog')])
When the method returns multiple values, it is better to return the results of namedtuple, so that the program logic will be clearer and better maintained:
>>> from collections import namedtuple>>> def get_name():... name = namedtuple("name", ["first", "middle", "last"])... return name("John", "You know nothing", "Snow")...>>> name = get_name()>>> print name.first, name.middle, name.lastJohn You know nothing Snow
Compared with tuple and dictionary, namedtuple is a little more complex: intuitive and easy to use. we recommend that you use namedtuple when appropriate.