Junior — Middle
Can you explain what an object with immutable properties in Python is and how it works?
sobes.tech AI
Answer from AI
In Python, an object with immutable properties is an object whose attribute values cannot be changed after creation. Such objects ensure data safety and predictable behavior, as their state does not change.
Examples of immutable objects in Python include tuples (tuple), strings (str), numbers (int, float), etc. If you need to create a custom class with immutable properties, you can use @property without a setter or namedtuple from the collections module.
Example using @property:
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, p.y) # 1 2
# p.x = 5 # Error: cannot modify property
Thus, an object with immutable properties guarantees that its state will not change after creation.