152. collections.namedtuple for Immutable Objects
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p) # Output: Point(x=3, y=4)
print(p.x, p.y) # Output: 3 4from collections import namedtuple
Car = namedtuple('Car', ['make', 'model', 'year'])
car = Car('Toyota', 'Corolla', 2020)
# Access fields
print(car.make) # Output: Toyota
# Attempting to modify will raise an error
try:
car.year = 2022
except AttributeError as e:
print(e) # Output: "can't set attribute"Last updated