Junior — Middle
Is it possible to create an object in Python that cannot be modified after initialization?
sobes.tech AI
Answer from AI
In Python, you can create immutable objects in several ways. The simplest is to use built-in immutable types, such as tuples or strings. For your own classes, you can use:
namedtuplefrom thecollectionsmodule, which creates immutable objects with named fields.@dataclass(frozen=True)from thedataclassesmodule (Python 3.7+), which makes class instances immutable.- Override class methods to prevent attribute modification after initialization.
Example with dataclass:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
# p.x = 3 # will raise an error: cannot assign to field 'x'
Thus, after creating an object, its fields cannot be changed.