## collections.namedtuple()命名序列元素

 from collections import namedtuple

 Student = namedtuple("Student", ['name', 'age', 'id'])  # 返回一个名为Student的包含name, age, id 属性的类
stu1 = Student("Stanley", 22, '') # 实例化
print(stu1)
# Student(name='Stanley', age=22, id='001')
print(stu1.name)
# Stanley # namedtuple()创建的类的实例化对象支持所有普通元组操作,包括索引和解压,同样的,其元素不可修改
print(len(stu1))
#
name, age, s_id = stu1
print(name)
# Stanley stu1.name = "Lily"
# AttributeError: can't set attribute # 如果要修改元素,可以使用_replace()方法
# 此方法并不是修改某个属性,而是和元组修改一样,整体指向了新的不同属性值的地址 stu1 = stu1._replace(name="Lily")
print(stu1.name)
# Lily # 使用namedtuple命名序列元素相比于使用下标访问元素更加清晰,代码可读性更高 # 使用nametuple建立原型,设置默认值(初始值) Student = namedtuple("Student", ['name', 'age', 'nationality'])
student_prototype = Student('', 0, 'China') # Student类的初始值 def update(s):
return student_prototype._replace(**s) stu1 = {"name": "Stanley", "age": 22}
print(update(stu1))
# Student(name='Stanley', age=22, nationality='China')

参考资料:
  Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).

05-17 05:09
查看更多