namedtuple(命名元组)
namedtuple: 简单理解,就是在普通元组基础上增加了filed,元组中每个元素都对应一个filed。访问元组中元素时可以不用下标,而是用namedtuple.filed这种类似于属性访问的方式来访问元组中的元素。
使用namedtuple的场景一般是我们需要使用一个tuple。但是我们想增加代码可读性,通过对元组中各元素的位置对应一个有意义的filed name,以使我们的元组中元素的意义变得更直观。
另外,namedtuple额外也提供了一些,比如_asdict的方法,方便我们将其转化为dictionary。
更为重要的是,namedtuple与tuple一样是不可变类型,这可能是我们在选择使用这种数据结构时的一个重要考量。意味着它可以用做字典的key。 而类似的结构,比如dataclass则是可变类型。
from collections import namedtuple
# Create a namedtuple type, Point
Point = namedtuple("Point", "x y")
issubclass(Point, tuple) # True
# Instantiate the new type
point = Point(2, 4)
print(point) # Point(x=2, y=4)
# Dot notation to access coordinates
point.x # 2
point.y # 4
# Indexing to access coordinates
point[0] # 2
point[1] # 4
# Named tuples are immutable
point.x = 100 # 报错: can't set attribute
namedtuple._replace(): namedtuple是不可变类型,一旦创建了实例,就不能修改其值。 可以用_replace方法来在原有namedtuple对象上创建一个新的对象,但指定某个filed值被更改。
from collections import namedtuple
Person = namedtuple("Person", "name age height")
jane = Person("Jane", 25, 1.75)
# After Jane's birthday
jane = jane._replace(age=26)
print(jane) # Person(name='Jane', age=26, height=1.75)

浙公网安备 33010602011771号