collections.namedtuple是一个工厂函数,它可以用来构建一个带字段名的元组和一个有名字的类,这个带名字的类对调式程序有很大的帮助。
"""具名元组"""
from collections import namedtuple
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
print(tokyo)
# City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667))
print(tokyo.population)
# 36.933
print(tokyo.coordinates)
# (35.689722, 139.691667)
print(tokyo[1])
# JP
>>>City._fileds
('name', 'country', 'population', 'coordinates')
>>>LatLong = namedtuple('LatLong', 'lat long')
>>>delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613899, 77.208889))
>>>delhi = City._make(delhi_data)
>>>delhi._asdict()
OrderedDict([('name', 'Delhi NCR'), ('country', 'IN'), ('population', 21.935), ('coordinates', LatLong(lat=28.613899, long=77.208889))])
>>>for key, value in delhi._asdict().items():
print(key + ':', value)
name: Delhi NCR
country: IN
population: 21.935
coordinates:LatLong(lat=28.613899, long=77.208889)
"""
_fileds属性是一个包括这个类所有字段名称的元组;
用_make()通过接受一个可迭代对象来生成这个类的一个实例,它的作用跟City(*delhi_data)一样;
_asdict()把具名元组以collections.OrderedDict的形式返回,我们可以利用它来把元组里的信息有好的呈现出来。
"""