Skip to content

命名元组(Named Tuple)

一句话解释

namedtuple 创建具有命名字段的不可变、可索引记录——数据类的轻量替代。

用大白话说

namedtuple 是每个位置都有名称的元组。你可以按名称(p.x)或按索引(p[0])访问字段,且它保持不可变和元组兼容。通过 collections.namedtuple('Name', ['field1', 'field2']) 或 typing.NamedTuple 子类(带类型注解)创建。命名元组比数据类占用更少内存,是轻量不可变记录的理想选择。它们支持解包(x, y = point)、可哈希(可用作字典键),并可用 ._make() 从可迭代对象创建或 ._replace() 创建修改副本。

示例

python
from collections import namedtuple
from typing import NamedTuple

# Classic style
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)    # 3 4
print(p[0])        # 3 (index access)
x, y = p           # Unpacking
print(p._replace(x=10))  # Point(x=10, y=4)

# Type-hint style (Python 3.6+)
class Color(NamedTuple):
    r: int
    g: int
    b: int

c = Color(255, 128, 0)
print(c)  # Color(r=255, g=128, b=0)

namedtuple 提供命名字段访问,同时保持真正的元组——不可变、可索引、可哈希、可解包。

常见混淆

  • 容易混淆的对象: 数据类

    关键区别: 命名元组不可变、元组兼容(可索引)、可哈希且内存轻量。数据类默认可变,轻松支持继承和方法,更灵活。简单不可变记录用命名元组,更丰富行为用数据类。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表