Lesson 8 of 15 · Behaviour
Magic Methods
Make your Python objects work with print, ==, <, +, len(), in and square brackets using magic methods such as __str__, __repr__, __eq__, __add__ and __len__.
- 8 min read
- Intermediate
- Reviewed
- What magic methods are and when Python calls them
- How to give objects a readable description with __str__ and __repr__
- How to make objects work with ==, < and sorting
- How to make + work on your own objects
- How to support len(), in and square brackets
Why built-in types feel special
You can print a list, add two numbers, compare two strings with == and ask len() of a dictionary. Your own objects cannot do any of this yet:
class Money:
def __init__(self, amount):
self.amount = amount
a = Money(100)
b = Money(100)
print(a)
print(a == b)The printout is unhelpful, and two equal amounts are reported as not equal. Magic methods fix both.
You never call magic methods yourself. You write them, and Python calls them at the right moment. __init__ is one you already know: Python calls it when an object is created.
Readable objects: __str__ and __repr__
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
def __repr__(self):
return f"Book({self.title!r}, {self.author!r})"
book = Book("Clean Code", "Robert Martin")
print(book)
print(str(book))
print(repr(book))
print([book, Book("Dune", "Frank Herbert")])!r inside the f-string shows a value with quotes around it, like code would. Notice the last line: when a list is printed, Python uses __repr__ for each item.
A good habit: always write a __repr__ for your classes. It makes debugging far easier. Add __str__ when you also want a nicer, plainer version for users.
Comparing objects: __eq__ and __lt__
Without __eq__, == only says True when both sides are the very same object. With it, you decide what "equal" means.
class Money:
def __init__(self, amount):
self.amount = amount
def __eq__(self, other):
return self.amount == other.amount
def __lt__(self, other):
return self.amount < other.amount
def __repr__(self):
return f"Money({self.amount})"
a = Money(100)
b = Money(100)
c = Money(40)
print(a == b)
print(c < a)
print(a > c)
print(sorted([a, c, Money(75)]))Defining __lt__ gave us three things: c < a, a > c (Python cleverly flips it round to c < a) and sorted().
Making + work: operator overloading
For +, the magic method is __add__. It should return a new object and leave both originals unchanged, just as 2 + 3 does not change the 2.
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return Money(self.amount + other.amount)
def __str__(self):
return f"Rs {self.amount}"
lunch = Money(150)
coffee = Money(80)
bill = lunch + coffee
print(bill)
print(lunch)lunch + coffee becomes lunch.__add__(coffee), so self is lunch and other is coffee.
Acting like a collection: __len__, __contains__ and __getitem__
class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add(self, song):
self.songs.append(song)
def __len__(self):
return len(self.songs)
def __contains__(self, song):
return song in self.songs
def __getitem__(self, index):
return self.songs[index]
mix = Playlist("Study mix")
mix.add("Lo-fi beats")
mix.add("Rain sounds")
mix.add("Piano focus")
print(len(mix))
print("Rain sounds" in mix)
print(mix[0])
print(mix[-1])Your playlist now behaves like a real Python collection, while still keeping its own name and rules.
A quick reference
| You write | Python calls | Typical use |
|---|---|---|
Book(...) | __init__ | set up a new object |
print(obj), str(obj) | __str__ | friendly text |
repr(obj), a list of objects | __repr__ | exact, developer text |
a == b | __eq__ | equality |
a < b, sorted(...) | __lt__ | ordering |
a + b | __add__ | adding |
len(obj) | __len__ | size |
x in obj | __contains__ | membership |
obj[i] | __getitem__ | indexing |
There are many more, such as __sub__ for - and __mul__ for *, and they all follow the same idea.
Common mistakes
Teach a Vector class to add, compare and describe itself. Vectors like this are the building blocks of machine learning maths.
# Write a class called Vector for a 2D arrow with x and y. # - __init__(self, x, y) # - __add__ returns a new Vector with the x values added and the y values added # - __eq__ returns True when both x and y match # - __str__ returns text like "Vector(4, 6)" a = Vector(1, 2) b = Vector(3, 4) print(a + b) print(a + b == Vector(4, 6)) print(a == b) # Output must be exactly: # Vector(4, 6) # True # False
Which magic method does Python call when you write len(playlist)?
Summary
- Magic methods are dunder methods that Python calls when you use built-in features on your objects.
__str__gives friendly text forprint.__repr__gives exact text for developers.__eq__and__lt__power==,<and sorting.__add__and friends are operator overloading. Return a new object, do not change the old ones.__len__,__contains__and__getitem__let objects act like collections.
You have finished the Behaviour module. Next: building new classes on top of existing ones with inheritance.
Finished reading? Tick it off to track your progress.