namedtuple用于创建轻量级不可变对象,支持属性访问和默认值(Python 3.7+),语法简洁,适合表示简单数据结构。
在 Python 中,
namedtuple
是
模块提供的一种用来创建轻量级、不可变的类对象的工厂函数。它能让你像定义类一样创建具有命名字段的元组,但语法更简洁。
使用 namedtuple 定义一个类(实际是命名元组)
通过
可以快速生成一个类,这个类的行为类似于元组,但每个位置的值都有名字,可按属性访问。
基本语法如下:
from collections import namedtupleClassName = namedtuple('ClassName', ['field1', 'field2', ...])
例如,定义一个表示二维点的“类”:
立即学习
“
Python免费学习笔记(深入)
”;
from collections import namedtuplePoint = namedtuple('Point', ['x', 'y'])p = Point(10, 20)print(p.x) # 输出: 10print(p.y) # 输出: 20print(p) # 输出: Point(x=10, y=20)
支持字段名字符串写法
你也可以将字段名写成一个空格或逗号分隔的字符串:
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
下载
Point = namedtuple('Point', 'x y')# 或者Point = namedtuple('Point', 'x, y')
支持默认值(Python 3.7+)
从 Python 3.7 开始,
支持为字段设置默认值:
Person = namedtuple('Person', ['name', 'age'], defaults=[18])p1 = Person('Alice', 25) # 全部传参p2 = Person('Bob') # age 使用默认值 18print(p2) # 输出: Person(name='Bob', age=18)
namedtuple 创建的是不可变对象
和普通元组一样,namedtuple 实例一旦创建就不能修改字段值:
p = Point(10, 20)# p.x = 15 # 错误!会抛出 AttributeError
如果需要可变对象,考虑使用
或普通类。
基本上就这些。namedtuple 适合用于存储简单、不可变的数据结构,代码清晰且性能好。
collectionsnamedtuplenamedtupledataclass