Skip to main content

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

MethodPurpose
__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 NotImplemented when comparison doesn't apply.
  • Update __hash__ whenever you override __eq__.

Next up in your learning path