问题
你有一段通过下标访问列表或者元组中元素的代码,但是这样有时候会使得你的代码难以阅读, 于是你想通过名称来访问元素。
解决方案
好吧又又是这个collections库......
使用 collections.namedtuple
函数,例如我们经常使用一个 tuple
表示一个坐标点的时候
总结
collections.namedtuple
函数返回的是 tuple
类型的一个子类,能够支持原生 tuple
的所有操作
但需要注
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> point_1 = Point(x=5, y=6)
>>> point_1.x = 6
Traceback (most recent call last)
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
如果想要修改某一成员,只能重新创建一个实例了,可以使用_replace
方法
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> point_1 = Point(x=5, y=6)
>>> point_2 = point_1._replace(x=6)
>>> print(point_2)
Point(x=6, y=6)
适当使用 namedtuple
会让代码可读性更好,例如从数据库调用中返回了一个很大的元组列表,如果通过下标去操作其中的元素会让代码模糊不清
并且在某些时候可以更节省资源(比如用 namedtuple
代替不经常做更新的 dict
)
关于更多关于命名元组见collections.namedtuple
意的是,当创建了一个 namedtuple
后,成员是不能被改变的(这和原生 tuple
是一致的)