215. Immutable Class Design
🔹 1. Basic Immutable Class Using property
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🔍 Key Takeaway:
Using
@property, we prevent modifications after object creation.
🔹 2. Immutable Class with __slots__
__slots__🔍 Key Takeaway:
__slots__prevents dynamic attribute creation, making the class memory-efficient and immutable.
🔹 3. Using namedtuple for Immutable Objects
namedtuple for Immutable Objects🔍 Key Takeaway:
namedtupleis a built-in immutable class with fixed fields.
🔹 4. Using dataclasses with frozen=True
dataclasses with frozen=True🔍 Key Takeaway:
Setting
frozen=Truein@dataclassmakes the class immutable.
🔹 5. Enforcing Immutability with __setattr__
__setattr__🔍 Key Takeaway:
Overrides
__setattr__to block modifications.
🔹 6. Preventing Deletion with __delattr__
__delattr__🔍 Key Takeaway:
__delattr__prevents accidental deletions.
🔹 7. Immutable Singleton Class
🔍 Key Takeaway:
Ensures only one immutable instance exists.
🔹 8. Immutable Dictionary (MappingProxyType)
MappingProxyType)🔍 Key Takeaway:
MappingProxyTypecreates a read-only dictionary.
🔹 9. Immutable Object with Custom Hashing
🔍 Key Takeaway:
Immutable objects are hashable, allowing use in sets and dictionaries.
🔹 10. Enforcing Attribute Restrictions with __slots__ and property
__slots__ and property🔍 Key Takeaway:
__slots__and@propertyenforce immutability efficiently.
🚀 Summary: Immutable Class Design Techniques
Method
Key Benefit
@property Decorators
Prevent direct modification
__slots__
Prevents dynamic attribute creation & saves memory
namedtuple
Built-in immutable tuple-like object
@dataclass(frozen=True)
Simplifies immutable class creation
Overriding __setattr__
Blocks modification of attributes
Overriding __delattr__
Prevents deletion of attributes
Singleton Pattern
Ensures only one immutable instance
MappingProxyType
Creates a read-only dictionary
Custom __hash__ Implementation
Allows immutable objects in sets/dicts
Last updated