Magic methods (also called dunder methods) are special methods surrounded by double underscores that let you define how your class instances interact with Python’s built-in operations. When you use + on two objects, Python calls __add__. When you call len(), Python calls __len__. This reference covers the most commonly used magic methods organized by category.
Initialization and Lifecycle Method Triggered By Purpose __init__(self, ...) MyClass() Initialize instance attributes __new__(cls, ...) Before __init__ Control instance creation (rarely needed) __del__(self) Object garbage collected Cleanup (prefer context managers instead) class User: def __init__(self, name, email): self.name = name self.email = email user = User("Carl", "carl@example.com") String Representation Method Triggered By Purpose __str__(self) str(obj), print(obj) Human-readable string __repr__(self) repr(obj), REPL display Developer/debug string __format__(self, spec) format(obj, spec), f-strings Custom formatting class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" def __str__(self): return f"({self.x}, {self.y})" p = Point(3, 4) print(repr(p)) # Point(3, 4) print(p) # (3, 4) Comparison Operators Method Operator __eq__(self, other) == __ne__(self, other) != __lt__(self, other) < __le__(self, other) <= __gt__(self, other) > __ge__(self, other) >= from functools import total_ordering @total_ordering class Temperature: def __init__(self, celsius): self.celsius = celsius def __eq__(self, other): return self.celsius == other.celsius def __lt__(self, other): return self.celsius < other.celsius freezing = Temperature(0) boiling = Temperature(100) print(freezing < boiling) # True print(freezing >= boiling) # False (from @total_ordering) With @total_ordering, you only need __eq__ and one of __lt__/__gt__ — Python derives the rest.
...