Python Dunder Methods
OOP Core
Magic (Dunder) Methods
Special methods let your classes behave like built-ins. Learn which ones matter most and how to implement them correctly.
Common methods
| Method | Purpose |
|---|---|
__repr__ / __str__ | Developer vs user-facing display |
__len__ | Support len(obj) |
__bool__ | Truthiness (fallback to __len__) |
__iter__ / __next__ | Iteration |
__contains__ | Membership checks |
__eq__, __lt__ | Comparisons |
__enter__, __exit__ | Context managers |
Equality & hashing
class Currency:
def __init__(self, code: str):
self.code = code
def __eq__(self, other: object) -> bool:
if not isinstance(other, Currency):
return NotImplemented
return self.code == other.code
def __hash__(self) -> int:
return hash(self.code)
- Return
NotImplementedwhen comparison doesn't apply. - Update
__hash__whenever you override__eq__.