Collections.namedtuple函数
from collections import namedtuple
City = namedtuple('City', ['name', 'country'])
#City = namedtuple('City', 'name country') 这个写法也是可行的
Beijing = City('Beijing', 'China')
print(Beijing.country) #调用Beijing的country属性
namedtuple有两个主要参数:typename & field_names
typename的主要作用,是表明这一个类的名称,同时让我们在调用时能更加方便。
field_names则是用来储存关于typename的相关内容。
namedtuple的几个自带属性
>>> from collections import namedtuple
>>> City = namedtuple('City', 'name country population coordinates')
'''_fields属性会返回City的field_names'''
>>> City._fields
('name', 'country', 'population', 'coordinates')
'''单独为坐标写一个namedtuple,可以在访问时更易读'''
>>> LatLong = namedtuple('LatLong', 'lat long')
>>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
>>> delhi = City._make(delhi_data)
#相当于City(*delhi_data), 注意这里要加星号
>>> delhi
City(name='Delhi NCR', country='IN', population=21.935, coordinates=LatLong(lat=28.613889, long=77.208889))
>>> delhi.coordinates.lat
28.613889
'''_asdict会把对象以字典的形式返回'''
>>> delhi._asdict()
{'name': 'Delhi NCR', 'country': 'IN', 'population': 21.935, 'coordinates': LatLong(lat=28.613889, long=77.208889)}