Lesson 7 of 7 · Classes and Objects · 3 min read · Updated
Special methods
Teaching your objects to print nicely, compare, add and work with len() and in.
Methods with double underscores on both sides — special or dunder methods — are called by Python itself. Define them and your objects work with print, +, ==, sorted() and len() just like built-in types.
python
class Money:
def __init__(self, rupees):
self.rupees = rupees
def __str__(self):
return f"₹{self.rupees:,}"
def __repr__(self):
return f"Money({self.rupees})"
def __add__(self, other):
return Money(self.rupees + other.rupees)
def __eq__(self, other):
return self.rupees == other.rupees
def __lt__(self, other):
return self.rupees < other.rupees
fee = Money(4500)
fine = Money(250)
print(fee)
print(fee + fine)
print([fee, fine])
print(fee == Money(4500), fine < fee)
print(sorted([fee, fine]))
Output
₹4,500
₹4,750
[Money(4500), Money(250)]
True True
[Money(250), Money(4500)]
__str__— whatprint()shows: friendly, for users.__repr__— what you see inside a list or at the prompt: precise, for programmers.__add__makes+work;__eq__makes==compare values instead of identity.__lt__(less than) is allsorted(),min()andmax()need.
Length and membership
python
class Playlist:
def __init__(self, songs):
self.songs = list(songs)
def __len__(self):
return len(self.songs)
def __contains__(self, song):
return song in self.songs
morning = Playlist(["Morning Raga", "Rain Song"])
print(len(morning), "Rain Song" in morning)
Output
2 True
Note
For classes that mainly hold data, the standard dataclasses module writes __init__, __repr__ and __eq__ for you: put @dataclass above the class and list the fields with their types.
Which method decides what print(obj) shows?
Try this now
- Write a
Fractionclass with__str__(such as "3/4"),__add__and__eq__. - Give your Student class
__lt__by marks, then sort a list of students and print them.
Create a free account to save your progress, or sign in.