215. Immutable Class Design
πΉ 1. Basic Immutable Class Using property
propertyclass 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