Why does len(my_list) work, or a + b for numbers and strings, or for x in data? Behind each of these, Python calls a special method whose name starts and ends with two underscores, such as __len__, __add__ and __iter__. These are called magic methods or dunder methods (“double underscore”). By defining them in your own classes, your objects can be printed nicely, compared, added, sorted, indexed and looped over just like built-in types.
In this lesson you will learn
__str__and__repr__for printing- Arithmetic with
__add__,__mul__and__rmul__ - Comparison with
__eq__and__lt__, and why__hash__matters - Container behaviour:
__len__,__getitem__,__contains__,__iter__ - Callable objects with
__call__
You should know classes and objects.
A Money Class: Printing, Maths and Comparison
class Money:
def __init__(self, taka, paisa=0):
total = taka * 100 + paisa
self.paisa = total # store everything in paisa
def __repr__(self): # for developers: unambiguous
return f"Money({self.paisa // 100}, {self.paisa % 100})"
def __str__(self): # for users: readable
return f"৳{self.paisa // 100}.{self.paisa % 100:02d}"
def __add__(self, other): # m1 + m2
return Money(0, self.paisa + other.paisa)
def __mul__(self, n): # m * 3
return Money(0, self.paisa * n)
__rmul__ = __mul__ # 3 * m
def __eq__(self, other): # m1 == m2
return isinstance(other, Money) and self.paisa == other.paisa
def __lt__(self, other): # m1 < m2 (lets sorted() work)
return self.paisa < other.paisa
def __hash__(self): # needed again after defining __eq__
return hash(self.paisa)
def __bool__(self): # if m: ...
return self.paisa != 0
tea = Money(15)
snack = Money(32, 50)
print(tea, snack, repr(snack))
print(tea + snack, 3 * tea, tea * 2)
print(Money(15) == tea, tea < snack, sorted([snack, tea, Money(5)]))
print(bool(Money(0)), len({Money(15), tea}))
Output
৳15.00 ৳32.50 Money(32, 50)
৳47.50 ৳45.00 ৳30.00
True True [Money(5, 0), Money(15, 0), Money(32, 50)]
False 1
- The amount is stored in whole paisa, which avoids floating-point rounding errors with money.
__str__is used byprint()andstr()and should be friendly for users.__repr__is used byrepr(), the interactive shell and inside lists, and should be unambiguous for developers. The sorted list showsreprvalues.__add__runs fortea + snackand__mul__fortea * 2. Python triesint.__mul__first for3 * tea; when that fails, it callstea.__rmul__(3), so both orders work.__eq__defines==. Without it, two equal amounts would be different objects and compare as false.__lt__defines<, which is allsorted()needs.functools.total_orderingcan fill in<=,>and>=from it.- Defining
__eq__removes the default__hash__, so__hash__is added back to allow use in sets and as dictionary keys. Equal amounts hash the same, so the set holds one item. __bool__decides truthiness, soif amount:is false for zero.
A Playlist Class: Acting Like a Container
class Playlist:
def __init__(self, name, songs=None):
self.name = name
self.songs = list(songs or [])
def __len__(self): # len(p)
return len(self.songs)
def __getitem__(self, index): # p[0], p[-1], p[1:3] and for-loops
if isinstance(index, slice):
return Playlist(self.name + " (part)", self.songs[index])
return self.songs[index]
def __contains__(self, song): # "x" in p
return song.lower() in (s.lower() for s in self.songs)
def __iter__(self): # for song in p
return iter(self.songs)
def __call__(self, n): # p(2): the object acts like a function
return f"Now playing: {self.songs[n]}"
def __repr__(self):
return f"Playlist({self.name!r}, {len(self)} songs)"
p = Playlist("Monsoon", ["Song A", "Song B", "Song C", "Song D"])
print(len(p), p[0], p[-1])
print(p[1:3], p[1:3].songs)
print("song b" in p, "Song Z" in p)
print([s.upper() for s in p])
print(p(2))
print(repr(p))
Output
4 Song A Song D
Playlist('Monsoon (part)', 2 songs) ['Song B', 'Song C']
True False
['SONG A', 'SONG B', 'SONG C', 'SONG D']
Now playing: Song C
Playlist('Monsoon', 4 songs)
__len__makeslen(p)work.__getitem__handlesp[0]andp[-1]. When the index is aslice, it returns a newPlaylist, just as slicing a list returns a list.__contains__controls theinoperator; here it ignores capital letters.__iter__returns an iterator, so the object works inforloops and comprehensions.__call__lets an object be called like a function:p(2).{self.name!r}in__repr__shows the name with quotes, making clear it is a string.
Common Magic Methods
| Method | Called by |
|---|---|
__init__ | Creating an object: Money(15) |
__str__, __repr__ | print(x), repr(x) |
__eq__, __lt__, __le__, __gt__ | ==, <, <=, > |
__add__, __sub__, __mul__, __truediv__ | +, -, *, / |
__len__, __getitem__, __setitem__ | len(x), x[i], x[i] = v |
__contains__, __iter__ | in, for loops |
__bool__, __hash__ | if x:, sets and dictionary keys |
__call__ | x() |
__enter__, __exit__ | with statements |
Common Mistakes
- Calling magic methods directly, such as
p.__len__(). Uselen(p); the built-in may do extra checks. - Defining
__eq__without__hash__, then being surprised the objects cannot go in a set. - Returning a string from
__len__or anything other than a non-negative integer. - Making
+do something surprising. Operators should behave the way readers expect.
Practice Exercises
Exercise 1. Add a __sub__ method to Money so Money(50) - Money(12, 50) prints ৳37.50.
Show answer
def __sub__(self, other):
return Money(0, self.paisa - other.paisa)
Exercise 2. Write a Vector class with x and y where Vector(1, 2) + Vector(3, 4) gives Vector(4, 6) and abs(Vector(3, 4)) gives 5.0.
Show answer
import math
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 __abs__(self):
return math.hypot(self.x, self.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4), abs(Vector(3, 4)))
Frequently Asked Questions
What if I define only __repr__ and not __str__?
Then print() and str() fall back to __repr__. Defining __repr__ is the more important of the two.
Do dataclasses write these methods for me?
Yes. A dataclass generates __init__, __repr__ and __eq__, and with order=True it also adds comparison methods.
Summary
- Magic methods connect your class to Python’s built-in syntax.
__repr__and__str__control printing.- Operators, comparisons,
len, indexing,inand loops all map to dunder methods. - When you define
__eq__, also define__hash__if the objects should go in sets.
Next: Python Logging.
