Dunder methods ("double underscore," also called magic/special methods) are specially-named methods like __init__, __str__, that let your objects integrate with Python's . Python calls them automatically in response to syntax — e.g. calls .
__len__len(obj)obj.__len__()class Vector:
def __init__(self, x, y): # constructor — Vector(1, 2)
self.x, self.y = x, y
def __repr__(self): # repr(v) and the REPL — for developers
return f"Vector({self.x}, {self.y})"
def __str__(self): # str(v) / print(v) — for users
return f"({self.x}, {self.y})"
def __add__(self, other): # enables the + operator: v1 + v2
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other): # enables ==
return self.x == other.x and self.y == other.y
v1, v2 = Vector(1, 2), Vector(3, 4)
v1 + v2 # Vector(4, 6) — calls __add__
print(v1) # (1, 2) — calls __str__
v1 == Vector(1, 2) # True — calls __eq__
Defining these lets your custom objects work with native syntax (+, ==, print) just like built-in types.
__init__ → constructor (object creation)
__repr__ → unambiguous developer representation (debugging, REPL)
__str__ → readable user-facing string (print, str())
__len__ → len(obj)
__getitem__→ obj[key] (indexing/subscripting)
__iter__ / __next__ → make an object iterable (for loops)
__eq__, __lt__, __gt__ → comparison operators (==, <, >)
__add__, __sub__, __mul__ → arithmetic operators
__call__ → make an instance callable like a function: obj()
__contains__ → the `in` operator
__enter__ / __exit__ → context managers (with statement)
class Deck:
def __init__(self): self.cards = [...]
def __len__(self): return len(self.cards) # len(deck)
def __getitem__(self, i): return self.cards[i] # deck[0], and iteration/slicing!
deck = Deck()
len(deck) # works
for card in deck: # __getitem__ makes it iterable too
...
Implementing __len__ and __getitem__ makes the object behave like a sequence — supporting len(), indexing, iteration, and slicing.
Dunder methods are how Python achieves its consistent, "everything is an object" feel — they let your custom classes integrate seamlessly with the language's operators and built-in functions (+, ==, len(), for, [], with, print).
This is the foundation of Python's elegant, polymorphic design ("duck typing" + the data model).
Knowing the key dunders — especially __init__, __repr__/__str__, comparison and arithmetic operators, and the iteration protocol — lets you build intuitive, Pythonic classes that feel like native types, and explains how the language's syntax maps onto method calls under the hood.