## collections.namedtuple()命名序列元素
1 from collections import namedtuple 2 3 4 Student = namedtuple("Student", ['name', 'age', 'id']) # 返回一个名为Student的包含name, age, id 属性的类 5 stu1 = Student("Stanley", 22, '001') # 实例化 6 print(stu1) 7 # Student(name='Stanley', age=22, id='001') 8 print(stu1.name) 9 # Stanley 10 11 12 # namedtuple()创建的类的实例化对象支持所有普通元组操作,包括索引和解压,同样的,其元素不可修改 13 print(len(stu1)) 14 # 3 15 name, age, s_id = stu1 16 print(name) 17 # Stanley 18 19 stu1.name = "Lily" 20 # AttributeError: can't set attribute 21 22 23 # 如果要修改元素,可以使用_replace()方法 24 # 此方法并不是修改某个属性,而是和元组修改一样,整体指向了新的不同属性值的地址 25 26 stu1 = stu1._replace(name="Lily") 27 print(stu1.name) 28 # Lily 29 30 # 使用namedtuple命名序列元素相比于使用下标访问元素更加清晰,代码可读性更高 31 32 33 # 使用nametuple建立原型,设置默认值(初始值) 34 35 Student = namedtuple("Student", ['name', 'age', 'nationality']) 36 student_prototype = Student('', 0, 'China') # Student类的初始值 37 38 def update(s): 39 return student_prototype._replace(**s) 40 41 stu1 = {"name": "Stanley", "age": 22} 42 print(update(stu1)) 43 # Student(name='Stanley', age=22, nationality='China')
参考资料:
Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).