Dunder ("double underscore") methods let custom classes participate in built-in syntax like arithmetic, comparisons, iteration, and container protocols.
python
class Money:
def __init__(self, cents):
self.cents = cents
def __add__(self, other):
return Money(self.cents + other.cents)
def __eq__(self, other):
return self.cents == other.cents
def __repr__(self):
return f"Money({self.cents})"
def __lt__(self, other):
return self.cents < other.cents
Money(100) + Money(50) # Money(150)
Money(100) == Money(100) # TrueImplementing `__lt__` (and optionally `functools.total_ordering` to fill in the rest) makes instances sortable with `sorted()`. `__len__` and `__getitem__` let a custom object behave like a sequence.