215. Immutable Class Design
πΉ 1. Basic Immutable Class Using property
propertyCopy
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__Copy
π Key Takeaway:
__slots__prevents dynamic attribute creation, making the class memory-efficient and immutable.
πΉ 3. Using namedtuple for Immutable Objects
namedtuple for Immutable ObjectsCopy
π Key Takeaway:
namedtupleis a built-in immutable class with fixed fields.
πΉ 4. Using dataclasses with frozen=True
dataclasses with frozen=TrueCopy
π Key Takeaway:
Setting
frozen=Truein@dataclassmakes the class immutable.
πΉ 5. Enforcing Immutability with __setattr__
__setattr__Copy
π Key Takeaway:
Overrides
__setattr__to block modifications.
πΉ 6. Preventing Deletion with __delattr__
__delattr__Copy
π Key Takeaway:
__delattr__prevents accidental deletions.
πΉ 7. Immutable Singleton Class
Copy
π Key Takeaway:
Ensures only one immutable instance exists.
πΉ 8. Immutable Dictionary (MappingProxyType)
MappingProxyType)Copy
π Key Takeaway:
MappingProxyTypecreates a read-only dictionary.
πΉ 9. Immutable Object with Custom Hashing
Copy
π Key Takeaway:
Immutable objects are hashable, allowing use in sets and dictionaries.
πΉ 10. Enforcing Attribute Restrictions with __slots__ and property
__slots__ and propertyCopy
π 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