Python Dunder Methods
Magic methods & the data model
The special methods that start and end with double underscores (__init__, __str__, __add__, …) let your classes integrate seamlessly with Python’s built-in syntax and protocols. Master them and your objects start behaving like native types.
🔮 What Are Dunder Methods?
Also called “magic methods” or “special methods”
The Python Data Model
Python is built around a set of protocols. When you write len(obj), Python doesn’t look for a method named len — it looks for __len__. When you write obj + other, it looks for __add__. When you print an object, it calls __str__ or __repr__.
These methods are intentionally named with double underscores (hence “dunder”) so they stand out from ordinary methods and are harder to call accidentally. You almost never call them directly — Python calls them for you when the corresponding syntax or built-in is used.
Why this matters
Implementing the right dunder methods makes your classes feel native. A custom Vector can support +, a custom File wrapper can be used with with, and a custom collection can respond to len(), indexing, and iteration — exactly like a list or dict.
Quick mental model
# What you write → What Python actually calls len(obj) → obj.__len__() str(obj) / print(obj) → obj.__str__() repr(obj) → obj.__repr__() obj + other → obj.__add__(other) obj[key] → obj.__getitem__(key) obj == other → obj.__eq__(other) with obj as x: → obj.__enter__() / obj.__exit__(...) for x in obj: → obj.__iter__()
🏗️ Object Creation & Representation
How objects are born and how they present themselves
__init__. Override __new__ when you need to control the actual object that is returned (immutable types, singletons, metaclasses).
__init__ — the constructor you use every day
class Person: def __init__(self, name: str, age: int): self.name = name self.age = age p = Person("Ana", 28) print(p.name, p.age)
__str__ vs __repr__
__str__ is for end users (readable). __repr__ is for developers (unambiguous, ideally recreatable). If only one is defined, Python falls back to the other in some contexts, but best practice is to implement both.
class Point: def __init__(self, x: float, y: float): self.x = x self.y = y def __repr__(self) -> str: # unambiguous, ideally eval-able return f"Point(x={self.x!r}, y={self.y!r})" def __str__(self) -> str: # human-friendly return f"({self.x}, {self.y})" p = Point(3.0, 4.5) print("str:", str(p)) print("repr:", repr(p)) print("in a list:", [p]) # uses __repr__
__repr__ should try to look like a valid Python expression that recreates the object. __str__ can be prettier and shorter.__format__ — custom format specs
class Money: def __init__(self, amount: float, currency: str = "USD"): self.amount = amount self.currency = currency def __format__(self, spec: str) -> str: if spec == "": return f"{self.amount:.2f} {self.currency}" if spec == "s": # short return f"{self.amount:.0f}{self.currency}" return format(self.amount, spec) + " " + self.currency m = Money(42.5) print(f"{m}") print(f"{m:s}") print(f"{m:.1f}")
⚖️ Comparison Methods
Making objects sortable and equality-aware
__eq__ for equality. For ordering, implement the rich comparison methods. From Python 3.11 you can also use @functools.total_ordering and only define __eq__ + one ordering method.
Equality and ordering
from functools import total_ordering @total_ordering class Student: def __init__(self, name: str, score: float): self.name = name self.score = score def __eq__(self, other): if not isinstance(other, Student): return NotImplemented return self.score == other.score def __lt__(self, other): if not isinstance(other, Student): return NotImplemented return self.score < other.score def __repr__(self): return f"Student({self.name!r}, {self.score})" s1 = Student("Ana", 92) s2 = Student("Ben", 88) s3 = Student("Cara", 92) print(s1 == s3) print(s1 > s2) print(sorted([s1, s2, s3]))
NotImplemented (not False or raise) when the other type is unsupported. This lets Python try the reflected method on the other object.__hash__ — making objects usable as dict keys / set members
If you define __eq__, Python sets __hash__ = None (the class becomes unhashable). To restore hashability, implement a consistent __hash__ based on the same fields used in __eq__. Mutable objects should usually stay unhashable.
class Coordinate: def __init__(self, x: int, y: int): self.x = x self.y = y def __eq__(self, other): return isinstance(other, Coordinate) and (self.x, self.y) == (other.x, other.y) def __hash__(self): return hash((self.x, self.y)) def __repr__(self): return f"Coordinate({self.x}, {self.y})" points = {Coordinate(1, 2), Coordinate(3, 4), Coordinate(1, 2)} print(points) print(Coordinate(1, 2) in points)
➕ Arithmetic & Operator Overloading
Let your objects use +, -, *, /, //, %, **, @ and the in-place variants
A simple Vector class
class Vector: def __init__(self, x: float, y: float): self.x = x self.y = y def __repr__(self): return f"Vector({self.x}, {self.y})" def __add__(self, other): if not isinstance(other, Vector): return NotImplemented return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): if not isinstance(other, Vector): return NotImplemented return Vector(self.x - other.x, self.y - other.y) def __mul__(self, scalar): if not isinstance(scalar, (int, float)): return NotImplemented return Vector(self.x * scalar, self.y * scalar) def __rmul__(self, scalar): # scalar * vector return self.__mul__(scalar) def __abs__(self): return (self.x ** 2 + self.y ** 2) ** 0.5 def __bool__(self): return bool(self.x or self.y) v1 = Vector(2, 3) v2 = Vector(1, -1) print(v1 + v2) print(v1 * 3) print(2 * v1) print(abs(v1)) print(bool(Vector(0, 0)))
__radd__, __rmul__, …) are called when the left operand does not know how to handle the right operand. They let expressions like 3 * vector work even though the integer doesn’t know about your class.| Operator | Method | In-place | Reflected |
|---|---|---|---|
+ | __add__ | __iadd__ | __radd__ |
- | __sub__ | __isub__ | __rsub__ |
* | __mul__ | __imul__ | __rmul__ |
/ | __truediv__ | __itruediv__ | __rtruediv__ |
// | __floordiv__ | __ifloordiv__ | __rfloordiv__ |
% | __mod__ | __imod__ | __rmod__ |
** | __pow__ | __ipow__ | __rpow__ |
@ | __matmul__ | __imatmul__ | __rmatmul__ |
- (unary) | __neg__ | — | — |
+ (unary) | __pos__ | — | — |
abs() | __abs__ | — | — |
📦 Container Protocol
Make custom objects work with len(), indexing, membership and iteration
A minimal custom sequence
class Playlist: def __init__(self, tracks=None): self._tracks = list(tracks) if tracks else [] def __len__(self): return len(self._tracks) def __getitem__(self, index): return self._tracks[index] def __setitem__(self, index, value): self._tracks[index] = value def __delitem__(self, index): del self._tracks[index] def __contains__(self, item): return item in self._tracks def __iter__(self): return iter(self._tracks) def __repr__(self): return f"Playlist({self._tracks!r})" def add(self, track): self._tracks.append(track) pl = Playlist(["Song A", "Song B", "Song C"]) print(len(pl)) print(pl[1]) print("Song B" in pl) for track in pl: print("→", track) pl[0] = "Intro" print(pl)
__getitem__ (and optionally __len__) is enough for Python to treat the object as a sequence in many contexts — including iteration and the in operator (via a linear scan).__reversed__ and slicing
Because __getitem__ already accepts slices, most sequence behaviour comes for free. You can still provide a more efficient __reversed__ if needed.
class Countdown: def __init__(self, start: int): self.start = start def __len__(self): return self.start + 1 def __getitem__(self, index): if isinstance(index, slice): return [self[i] for i in range(*index.indices(len(self)))] if index < 0: index += len(self) if 0 <= index <= self.start: return self.start - index raise IndexError(index) c = Countdown(5) print(list(c)) print(c[2]) print(c[1:4]) print(list(reversed(c)))
🔑 Attribute Access
Intercepting and controlling how attributes are looked up and set
__getattr__ — fallback for missing attributes
Called only when the normal lookup fails. Useful for lazy attributes, proxies, or dynamic APIs.
class Config: def __init__(self): self._data = {"host": "localhost", "port": 8080} def __getattr__(self, name): if name in self._data: return self._data[name] raise AttributeError(f"{type(self).__name__!r} has no attribute {name!r}") cfg = Config() print(cfg.host) print(cfg.port) # print(cfg.missing) → AttributeError
__setattr__ and controlled mutation
Override carefully — it is easy to create infinite recursion. Always write through object.__setattr__ or super().__setattr__.
class Frozen: def __init__(self, **kwargs): for k, v in kwargs.items(): object.__setattr__(self, k, v) object.__setattr__(self, "_frozen", True) def __setattr__(self, name, value): if getattr(self, "_frozen", False): raise AttributeError(f"Cannot set {name!r} on frozen instance") object.__setattr__(self, name, value) def __repr__(self): data = {k: v for k, v in self.__dict__.items() if not k.startswith("_")} return f"Frozen({data})" f = Frozen(x=10, y=20) print(f) try: f.x = 99 except AttributeError as e: print("Error:", e)
@property and descriptors for most attribute control. Reach for __getattr__ / __setattr__ only when you need truly dynamic behaviour.📞 Making Objects Callable — __call__
Instances that behave like functions
Stateful callables and simple decorators
class Counter: def __init__(self): self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 return self.count c = Counter() print(c()) print(c()) print(c()) print("Total calls:", c.count) # A tiny decorator implemented with __call__ class once: def __init__(self, func): self.func = func self.called = False self.result = None def __call__(self, *args, **kwargs): if not self.called: self.result = self.func(*args, **kwargs) self.called = True return self.result @once def expensive(): print("Computing…") return 42 print(expensive()) print(expensive())
🚪 Context Managers — __enter__ & __exit__
The protocol behind the with statement
A simple timer context manager
import time class Timer: def __enter__(self): self.start = time.perf_counter() return self # becomes the target of "as" def __exit__(self, exc_type, exc_val, exc_tb): elapsed = time.perf_counter() - self.start print(f"Elapsed: {elapsed:.4f}s") return False # do not suppress exceptions with Timer() as t: total = sum(i * i for i in range(100_000)) print("Sum of squares:", total)
__exit__ receives the exception info if one occurred. Returning a true value suppresses the exception; returning false (or None) lets it propagate.Suppressing selected exceptions
class suppress: def __init__(self, *exceptions): self.exceptions = exceptions def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): return exc_type is not None and issubclass(exc_type, self.exceptions) with suppress(ValueError, ZeroDivisionError): print(1 / 0) # silently ignored print("Still running")
Prefer contextlib for simple cases
For many one-off context managers, @contextlib.contextmanager is clearer than writing a full class. Reach for __enter__ / __exit__ when you need a reusable, stateful object.
✅ Best Practices & Pitfalls
Patterns that keep dunder methods maintainable
- ✓Always return
NotImplemented(not raise or return False) from binary operators when the other type is unsupported. - ✓Keep
__eq__and__hash__consistent. If two objects compare equal, their hashes must be equal. - ✓Prefer
__repr__that looks like a constructor call; fall back to a useful string for__str__. - ✓Do not call dunder methods directly in application code — use the corresponding built-in or operator.
- ✓Be extremely careful with
__setattr__and__getattribute__; they are easy to break. - ✓For most attribute control, use
@property, descriptors, or dataclasses instead of low-level dunders. - ✓Document the invariants your dunder methods rely on — future maintainers (including you) will thank you.
❓ Frequently Asked Questions
Do I need to implement every dunder method?
No. Implement only the ones that make sense for your class. A simple data container may only need __init__, __repr__, and __eq__. A numeric type will add arithmetic methods. A context manager only needs __enter__ and __exit__.
Is there a performance cost?
Calling a dunder method through an operator or built-in is roughly the same cost as a normal method call. The main cost is the extra Python-level method dispatch; for hot numeric loops you may still want NumPy or a C extension.
What about __slots__?
__slots__ is a class attribute that tells Python to allocate a fixed set of attributes instead of a per-instance __dict__. It saves memory and can speed up attribute access, but it restricts dynamic attribute creation and has inheritance caveats. Use it when you have many instances of a simple class.
Where can I see the full list?
The official reference is the Data Model chapter in the Python documentation. The sections on “Emulating container types”, “Emulating numeric types”, and “Emulating callable objects” are especially useful.
🚀 What’s Next?
Continue building your OOP and advanced Python foundation
Python Classes
Solidify the basics of defining classes, methods, and the self parameter.
Continue →Decorators In Depth
Many decorators rely on callable objects and closures — a natural next step.
Continue →Context Managers
Deep dive into the with statement, contextlib, and real-world resource management.
Continue →Iterators & Generators
__iter__ and __next__ are only the beginning of the iterator protocol.
Continue →