Tuple thường truy cập phần tử bằng chỉ số (index). Named tuple cho phép truy cập bằng tên trường (attribute), code dễ đọc hơn.
Tạo named tuple
from collections import namedtuple
Student = namedtuple('Student', ['rollno', 'name', 'age', 'marks'])
# hoặc: 'rollno name age marks' (chuỗi phân cách space)
s1 = Student(1, "Ravi", 23, 546)
print(s1) # Student(rollno=1, name='Ravi', age=23, marks=546)
print(s1.rollno) # 1
print(s1.name) # 'Ravi'
print(s1[0]) # 1 (vẫn truy cập bằng index được)
Đặc điểm
- Immutable như tuple thường.
- Nhẹ hơn class thường (không có
__dict__). - Hữu ích cho record dữ liệu đơn giản, return nhiều giá trị từ hàm.
Phương thức hữu ích
s1._asdict() # {'rollno': 1, 'name': 'Ravi', 'age': 23, 'marks': 546}
s1._replace(age=24) # trả về named tuple mới với age=24
Student._fields # ('rollno', 'name', 'age', 'marks')