215. Immutable Class Design
class ImmutablePoint:
def __init__(self, x, y):
self._x = x # Private variable
self._y = y
@property
def x(self):
return self._x
@property
def y(self):
return self._y
p = ImmutablePoint(3, 4)
print(p.x) # ✅ 3
p.x = 10 # ❌ AttributeError: can't set attribute🔹 2. Immutable Class with __slots__
__slots__🔹 3. Using namedtuple for Immutable Objects
namedtuple for Immutable Objects🔹 4. Using dataclasses with frozen=True
dataclasses with frozen=True🔹 5. Enforcing Immutability with __setattr__
__setattr__🔹 6. Preventing Deletion with __delattr__
__delattr__🔹 7. Immutable Singleton Class
🔹 8. Immutable Dictionary (MappingProxyType)
MappingProxyType)🔹 9. Immutable Object with Custom Hashing
🔹 10. Enforcing Attribute Restrictions with __slots__ and property
__slots__ and property🚀 Summary: Immutable Class Design Techniques
Last updated