Junior — Middle
What ways in Python can prevent the modification of an object's state after its creation?
sobes.tech AI
Answer from AI
In Python, to prevent modification of an object's state after its creation, several approaches can be used:
-
Using immutable data types — for example, tuples instead of lists.
-
Defining read-only properties with the
@propertydecorator without a setter:
class ImmutablePoint:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@property
def y(self):
return self._y
p = ImmutablePoint(1, 2)
print(p.x) # 1
# p.x = 5 # AttributeError
-
Using
__slots__to restrict dynamic attribute addition. -
Creating immutable classes with
namedtupleordataclasseswithfrozen=Trueparameter:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
# p.x = 3 # Error, object is frozen
- Overriding methods that change state (e.g.,
__setattr__) to prohibit modifications after initialization.
These methods help create objects with immutable state, which is useful for data safety and multithreaded applications.