'''
collections是Python内建的一个集合模块,提供了许多有用的集合类。
collections.namedtuple是一个工厂方法,它可以动态的创建一个继承tuple的子类。跟tuple相比,返回的子类可以使用名称来访问元素。
namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。
'''
from collections import namedtuple
# namedtuple('名称', [属性list]):
Circle_d = namedtuple('Circle', ['x', 'y', 'r'])
a=Circle_d(1,2,3)
print(a)
print(a.x)
print(a._replace(x = 5))
# result:
# Circle(x=1, y=2, r=3)
# 1
# Circle(x=5, y=2, r=3)
下面官方的文档,我摘抄下来的
"""Returns a new subclass of tuple with named fields."""
Point = namedtuple('Point', ['x', 'y'])
print(Point.__doc__) # docstring for the new class)
# Point(x, y)
p = Point(11, y=22) # instantiate with positional args or keywords
print(p[0] + p[1]) # indexable like a plain tuple
# 33
x, y = p # unpack like a regular tuple
print(x, y)
# (11, 22)
print(p.x + p.y) # fields also accessible by name
# 33
print(p._replace(x=100)) # _replace() is like str.replace() but targets named fields
# Point(x=100, y=22)
d = p._asdict() # convert to a dictionary
print(d)
print(d['x'])
# 11
print(Point(**d)[1]) # convert from a dictionary
# Point(x=11, y=22)