Sobes.tech
Junior — Middle

How can you implement a class whose objects cannot be modified after creation?

sobes.tech AI

Answer from AI

To make class objects immutable after creation, you can:

  • Declare all attributes as private and do not provide setters.
  • Use @property with only a getter (in Python 3.8+ you can use @property without a setter).
  • Override attribute modification methods, such as __setattr__, to prevent changes after initialization.

Example:

class ImmutablePoint:
    def __init__(self, x, y):
        super().__setattr__('x', x)
        super().__setattr__('y', y)
        super().__setattr__('_locked', True)

    def __setattr__(self, key, value):
        if hasattr(self, '_locked') and self._locked:
            raise AttributeError(f"Cannot modify attribute '{key}' after object creation")
        super().__setattr__(key, value)

p = ImmutablePoint(1, 2)
print(p.x, p.y)  # 1 2
p.x = 10  # will raise AttributeError

This makes the object immutable after creation.