Collection.namedtuple is a factory function that can be used to construct a tuple with a field name and a class with a name-the class with the name is very helpful to the debugger. And an instance of a class built with namedtuple consumes the same amount of memory and tuples as the field names are in the corresponding class. This instance is smaller than the consumed object instance, because Python does not use __dict__ to store these attributes.
>>> from collections Import Namedtuple
>>> City = namedtuple (' city ', ' name country population coordinates ') (1)
>>> Tokyo = City (' Tokyo ', ' JP ', 36.933, (35.689722, 139.691667)) (2)
>>> Tokyo (' Tokyo ', ' JP ', 36.933, (35.689722, 139.691667))
>>> Tokyo[1]
' JP '
>>> tokyo.polution
36.993
>>> tokyo.coordinates (3)
(35.689722, 139.691667)
(1) Creating a named tuple requires two parameters, one is the class name and the other is the name of each field. The latter can be either an iterative object consisting of several strings, or a string of fields separated by spaces.
(2) The data stored in the corresponding field is passed into the constructor in the form of a string of parameters (the tuple's constructors accept only a single, iterative object)
(3) We can obtain a field information by field name or location information.
In addition to attributes inherited from common tuples, named tuples have their own proprietary properties. such as the _fields class property, the class method _make (Iterable), and the instance method _asdict ().
>>> City._fields ( 1) (' name ', ' country ', ' population ', ' coordinates ') >>> Latlong = Namedtuple (' Latlong ', ' lat long ') >>> delhi_data = (' Delhi NCR ', ' in ', 21.935, Latlong (28.613889, 77.208889)) >>> del hi = City._make (delhi_data) (2) >>> delhi._asdict () (3) ordereddict ([' Name ', ' Delhi NCR '), (' Country ', ' in '), (' Population ', 21.935), (' coordinates ', Latlong (lat=28.613889, long=77.208889))]) >>> for key, value In Delhi._asdict (). Items (): ... print (key + ': ', value) ... Name:delhi ncrcountry:inpopulation:21.935coordinates:latl Ong (lat=28.613889, long=77.208889) >>>
(1) The _field property is a tuple that contains all the field names for this class.
(2) using _make () to generate an instance of this class by accepting an iterative object, its role is the same as City (*delhi_data)
(3) _asdict () sets the named tuple to collection. Return in the form of ordereddict. Its second role is to act as a immutable list.
Python named tuples