Explain it simply
Explain it simply
Picture Python's syntax, +, ==, len(), print() and for, as a row of power sockets. Built-in types such as int, str and list already have every plug, which is why "a" + "b" and len([1, 2]) just work. A class you write yourself has no plugs yet, so v1 + v2 raises a TypeError.
Magic methods, also called dunder methods, are those plugs. Write __add__ and + starts working; write __len__ and len() works. You rarely call these methods yourself; Python calls them behind the scenes when it meets the matching syntax.
Problem → Why → Solution
The problem: useless printouts and == that is always False
Look at this Money class with no magic methods. print(price) shows only a memory address such as <__main__.Money object at 0x...>, so a log never tells you the amount. Worse, comparing two Money objects with equal values using == gives False, which makes tests fail in confusing ways.
class Money:
def __init__(self, amount, currency):
self.amount, self.currency = amount, currency
price = Money(5, "USD")
print(price) # <__main__.Money object at 0x...>
print(price == Money(5, "USD")) # FalseWhy does this happen?
Every class inherits default magic methods from object. The default __repr__ shows only the class name and memory address, and the default __eq__ only checks identity, the same as is. Python cannot know how your object should look or when two of them count as equal, so you tell it by overriding __repr__ and __eq__.
Core concept: hooks into Python's data model
Python's data model ties each piece of syntax to a magic method: len(x) calls type(x).__len__(x), a + b calls a.__add__(b), and x in c calls c.__contains__(x). The names have two underscores on each side, hence "dunder" for double underscore. Do not invent new dunder names; only the ones Python defines mean anything.
__repr__ and __str__ differ. __repr__ is for developers: precise and, when possible, code that would rebuild the object, such as Vector(1, 2). Lists of objects, debuggers and the REPL all use __repr__. __str__ is for end users and is used by print() and str(). If __str__ is missing, Python falls back to __repr__, so always write at least __repr__.
Operator methods follow one key rule: when the other operand is a type you do not support, return the special value NotImplemented instead of raising. Python then tries the other object's reflected method, such as __radd__, and only if nobody supports the operation does it raise a clear TypeError itself. For ==, it falls back to an identity comparison and returns False.
As soon as you define __eq__, Python sets __hash__ to None, so the object can no longer go into a set or be a dict key. To restore that, write __hash__ from the same fields __eq__ compares: whenever a == b, hash(a) == hash(b) must also hold. Do not change those fields after the object is stored in a set or dict.
Overload operators only where the meaning is natural. Adding two vectors or two amounts of money makes sense, but code like user + order only surprises the reader.
- Python meets a + b
- It calls a.__add__(b)
- NotImplemented? Try b.__radd__(a)
- Both decline: Python raises TypeError
len(), ==, in, for and print() each map to a dunder method in the same way.
General pattern
class MyType:
def __repr__(self): # repr(obj), REPL, lists
return f"MyType({self.field!r})"
def __eq__(self, other): # obj == other
if not isinstance(other, MyType):
return NotImplemented
return self.field == other.field
def __hash__(self): # needed again once __eq__ exists
return hash(self.field)Each magic method pairs with one piece of syntax. !r uses the value's repr(), so strings get quotes. Return NotImplemented for unknown types, and compute __hash__ from the same fields __eq__ compares.
Example: a Vector and a Bag
Vector demonstrates representation, arithmetic, equality and hashing, while Bag demonstrates the container protocol: len, indexing, iteration and in. Watch how NotImplemented turns into a TypeError on the line that tries v1 + 5.
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self): # for developers: repr(v), lists
return f"Vector({self.x}, {self.y})"
def __str__(self): # for humans: print(v), str(v)
return f"({self.x}, {self.y})"
def __add__(self, other): # v1 + v2
if not isinstance(other, Vector):
return NotImplemented # let Python try other options
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other): # v1 == v2
if not isinstance(other, Vector):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self): # keep hash consistent with ==
return hash((self.x, self.y))
class Bag:
def __init__(self, items):
self._items = list(items)
def __len__(self): # len(bag)
return len(self._items)
def __getitem__(self, index): # bag[0]
return self._items[index]
def __iter__(self): # for item in bag
return iter(self._items)
def __contains__(self, item): # "x" in bag
return item in self._items
v1, v2 = Vector(1, 2), Vector(3, 4)
print(v1 + v2)
print([v1, v2])
print(v1 == Vector(1, 2), len({v1, Vector(1, 2)}))
try:
v1 + 5
except TypeError as e:
print("TypeError:", e)
bag = Bag(["pen", "book", "cup"])
print(len(bag), bag[0], "cup" in bag)
print([item.upper() for item in bag])Code breakdown
- Lines 43-44
print([v1, v2])print(v1 + v2) uses __str__ and shows (4, 6), but printing a list uses __repr__ for each element, which is why you see Vector(1, 2).
- Line 13
return NotImplemented # let Python try other options5 is not a Vector, so the method returns NotImplemented. int does not know how to add a Vector either, so Python raises the "unsupported operand type(s)" TypeError.
- Line 45
print(v1 == Vector(1, 2), len({v1, Vector(1, 2)}))__eq__ makes equal values compare True. Because __hash__ agrees with ==, the set treats the two objects as one and its length is 1.
- Line 53
print(len(bag), bag[0], "cup" in bag)len() calls __len__, bag[0] calls __getitem__, and in calls __contains__.
- Line 54
print([item.upper() for item in bag])The for inside the comprehension calls __iter__ and pulls each item from the returned iterator.
(4, 6)
[Vector(1, 2), Vector(3, 4)]
True 1
TypeError: unsupported operand type(s) for +: 'Vector' and 'int'
3 pen True
['PEN', 'BOOK', 'CUP']| Category | Methods |
|---|---|
| Lifecycle | __init__, __new__, __del__ |
| Representation | __repr__, __str__, __format__ |
| Arithmetic | __add__, __sub__, __mul__, __truediv__ |
| Containers | __len__, __getitem__, __iter__ |
Comparison methods and sorted()
__lt__ (<), __le__ (<=), __gt__ (>) and __ge__ (>=) define ordering. sorted(), min() and max() rely mainly on __lt__, so writing __lt__ alone is enough to sort a list. If you want every comparison, the functools.total_ordering decorator fills in the rest from __eq__ and __lt__. For a data class, @dataclass(order=True) generates all of them in field order.
| Syntax | Method called |
|---|---|
| a < b | a.__lt__(b) |
| a - b, a * b | a.__sub__(b), a.__mul__(b) |
| 5 + a (a on the right) | a.__radd__(5) |
| bool(a), if a: | a.__bool__(), else __len__ |
| with a: | a.__enter__(), a.__exit__(...) |
In real projects
Where this shows up in real projects
Big libraries feel like built-in Python because of magic methods. In NumPy, a + b adds arrays element by element thanks to __add__; in pandas, df["price"] works through __getitem__; in pathlib, Path("data") / "file.csv" uses __truediv__. Django QuerySets support len(), slicing and for loops through container methods.
In your own application code, a single __repr__ saves a lot of time. When an error log shows Order(id=1042, status='paid') instead of <Order object at 0x7f...>, you know at once which order failed. Value objects such as Money, Coordinate or DateRange with __eq__ and __hash__ can be set members and dict keys, and tests can use simple checks such as assert total == Money(10, "USD").
Common mistakes
Common mistakes
1. Defining __eq__ and losing hashability
Writing __eq__ without __hash__ makes {Vector(1, 2)} fail with "TypeError: unhashable type: 'Vector'". If the object is used as immutable, write __hash__ from the same fields as __eq__; if it is mutable, leaving it unhashable is correct.
2. Returning False or raising instead of NotImplemented
Raising TypeError("bad") inside __add__ for an unknown type denies the other class the chance to handle it with __radd__. Returning False from __eq__ likewise blocks the other side's comparison. Return NotImplemented, and do not confuse it with raise NotImplementedError.
3. __repr__ or __str__ returning a non-string
Returning a number such as self.amount makes print() fail with "TypeError: __str__ returned non-string". Likewise __len__ must return an integer of 0 or more. Every dunder method comes with rules about what it returns.
Best practices
Best practices
- Write __repr__ first in every new class: it costs the least time and pays off the most during debugging.
- For classes that only hold data, use @dataclass instead of hand-writing __init__, __repr__ and __eq__; add frozen=True for immutability and you get __hash__ too.
- When you overload one operator, keep related ones consistent: if a + b works, a - b and a += b should behave as readers expect.
- Keep __len__ cheap, because every if obj: may call it.
Mini challenge
Mini challenge: a Money value object
Use magic methods to write a Money class that can be added, compared, sorted and easily debugged.
- __repr__ returns the form Money(10, 'USD')
- __add__ adds only matching currencies, raises ValueError otherwise, and returns NotImplemented for non-Money
- __eq__ is True only when both amount and currency match
- Write __lt__ and show sorted() and min() working
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __repr__(self):
# TODO: return "Money(10, 'USD')" (hint: !r adds the quotes)
pass
# TODO: __add__ : NotImplemented for non-Money, ValueError for mixed currency
# TODO: __eq__ : compare amount and currency
# TODO: __lt__ : compare amounts of the same currency
# TODO: prices = three USD amounts; print a sum, sorted(prices) and min(prices)
# TODO: show that adding USD to EUR raises ValueErrorExpected: Expected output: Money(10, 'USD') [Money(3, 'USD'), Money(5, 'USD'), Money(7, 'USD')] True Money(3, 'USD') error: cannot add different currencies
Show hint
f"Money({self.amount}, {self.currency!r})" shows the currency in quotes. sorted() only needs __lt__, so __gt__ is optional.
Show solution
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __repr__(self):
return f"Money({self.amount}, {self.currency!r})"
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
if other.currency != self.currency:
raise ValueError("cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.amount, self.currency) == (other.amount, other.currency)
def __lt__(self, other):
if not isinstance(other, Money) or other.currency != self.currency:
return NotImplemented
return self.amount < other.amount
__hash__ = None # Python does this anyway once __eq__ exists
prices = [Money(7, "USD"), Money(3, "USD"), Money(5, "USD")]
print(prices[0] + prices[1])
print(sorted(prices))
print(Money(3, "USD") == prices[1], min(prices))
try:
Money(1, "USD") + Money(1, "EUR")
except ValueError as e:
print("error:", e)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Magic methods connect syntax such as +, ==, len(), in, for and print() to your own classes.
- __repr__ is for developers and __str__ for users; always write at least __repr__.
- Operator methods return NotImplemented for types they do not support.
- When you define __eq__, write __hash__ from the same fields or leave the class unhashable.
Python Documentation — Classes — Python Software Foundation