Python Magic Methods
Magic methods (also called dunder methods, for "double underscore") are specially named methods like __init__, __str__ and __add__. You rarely call them yourself; Python calls them when you use built-in syntax. a + b becomes a.__add__(b), len(x) becomes x.__len__(), and x[0] becomes x.__getitem__(0).
Implementing them lets your own classes behave like built-in types.
String representations: __str__ and __repr__
| Method | Called by | Audience |
|---|---|---|
__str__ |
print(x), str(x), f-strings |
end users — friendly text |
__repr__ |
repr(x), the REPL, inside containers |
developers — unambiguous, ideally valid code |
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __str__(self):
return f"{self.amount:,.2f} {self.currency}"
def __repr__(self):
return f"Money({self.amount!r}, {self.currency!r})"
m = Money(1250.5, "USD")
print(m)
print(repr(m))
print([m]) # containers use repr for their items1,250.50 USD
Money(1250.5, 'USD')
[Money(1250.5, 'USD')]
If you only write one, write __repr__: str() falls back to it.
Arithmetic operators
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar): # handles 3 * v
return self * scalar
def __abs__(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def __repr__(self):
return f"Vector({self.x}, {self.y})"
a = Vector(1, 2)
b = Vector(3, 4)
print(a + b)
print(b - a)
print(a * 3)
print(3 * a)
print(abs(b))Vector(4, 6)
Vector(2, 2)
Vector(3, 6)
Vector(3, 6)
5.0
__rmul__ ("reflected multiply") is tried when the left operand (3, an int) doesn't know how to multiply by a Vector.
Comparisons and hashing
from functools import total_ordering
@total_ordering
class Card:
RANKS = "23456789TJQKA"
def __init__(self, rank):
self.rank = rank
def __eq__(self, other):
return self.rank == other.rank
def __lt__(self, other):
return self.RANKS.index(self.rank) < self.RANKS.index(other.rank)
def __hash__(self):
return hash(self.rank)
def __repr__(self):
return f"Card({self.rank!r})"
hand = [Card("K"), Card("3"), Card("A"), Card("T")]
print(sorted(hand))
print(Card("Q") >= Card("J"))
print(len({Card("A"), Card("A")}))[Card('3'), Card('T'), Card('K'), Card('A')]
True
1
@total_ordering fills in <=, > and >= from __eq__ and __lt__. If you define __eq__, also define __hash__ when the object should work in sets or as a dict key.
Container behaviour
Make an object act like a collection with __len__, __getitem__, __contains__ and __iter__:
class Deck:
def __init__(self):
self.cards = [r + s for s in "♠♥" for r in "AKQ"]
def __len__(self):
return len(self.cards)
def __getitem__(self, index):
return self.cards[index]
def __contains__(self, card):
return card in self.cards
d = Deck()
print(len(d))
print(d[0], d[-1])
print(d[1:3]) # slicing works too
print("Q♥" in d)
for card in d: # __getitem__ alone makes it iterable
print(card, end=" ")
print()6
A♠ Q♥
['K♠', 'Q♠']
True
A♠ K♠ Q♠ A♥ K♥ Q♥
Callable objects
__call__ lets an instance be called like a function, which is useful for objects that carry configuration:
class Discount:
def __init__(self, percent):
self.percent = percent
def __call__(self, price):
return round(price * (1 - self.percent / 100), 2)
sale = Discount(20)
print(sale(50))
print(list(map(sale, [10, 99.99])))40.0
[8.0, 79.99]
Cheat sheet
| Syntax | Magic method |
|---|---|
Obj(...) |
__init__ |
str(x), repr(x) |
__str__, __repr__ |
x + y, x - y, x * y, x / y |
__add__, __sub__, __mul__, __truediv__ |
x == y, x < y |
__eq__, __lt__ |
len(x) |
__len__ |
x[k], x[k] = v |
__getitem__, __setitem__ |
k in x |
__contains__ |
for i in x |
__iter__ |
x() |
__call__ |
with x: |
__enter__, __exit__ |
bool(x) |
__bool__ (falls back to __len__) |
Tip: Return
NotImplemented(notFalse) from an operator method when it can't handle the other operand's type. Python will then try the other operand's reflected method.
Test yourself
Which magic method does a + b call?
- __plus__
- __add__
- __sum__
- __concat__
Which method is used to show objects inside a printed list?
- __str__
- __repr__
- __format__
- __print__
What does implementing __call__ allow?
- Calling the class without arguments
- Calling an instance like a function
- Calling methods without self
- Automatic logging