After this lesson your own classes will work naturally with print, ==, len(), + and sorted().
What special methods are
Python lets you write len(items), a + b and print(x) on built-in types. Behind the scenes, each of these is turned into a method call. For example a + b becomes a.__add__(b). These methods have double underscores on each side, which is why they are called dunder methods (double underscore).
You can define them in your own class. The rule to remember is this: you rarely call them yourself. You write the normal syntax, and Python calls the special method.
Printing: __str__ and __repr__
Printing an object of a plain class gives an unhelpful result, because Python has no idea what you want to show. Define __str__ to control print and str():
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title} ({self.pages} pages)"
def __repr__(self):
return f"Book({self.title!r}, {self.pages!r})"
novel = Book("The Silent Garden", 320)
print(novel)
print(repr(novel))
print([novel])The Silent Garden (320 pages)
Book('The Silent Garden', 320)
[Book('The Silent Garden', 320)]__str__ is for readers: short and friendly. __repr__ is for developers: precise, ideally looking like the code that would rebuild the object. Python uses __repr__ when an object sits inside a list, as the last line shows. If you only have time to write one, write __repr__, since print falls back to it.
Comparing: __eq__ and __lt__
By default, == on two objects asks "are these the very same object?". Usually you want to compare the contents:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2) == Point(1, 2))
print(Point(1, 2) == Point(3, 4))True
FalseTo make objects sortable, define __lt__ ("less than"). sorted() and min() only need that one:
class Student:
def __init__(self, name, mark):
self.name = name
self.mark = mark
def __lt__(self, other):
return self.mark < other.mark
def __repr__(self):
return f"Student({self.name!r}, {self.mark})"
group = [Student("Asha", 82), Student("Ben", 74), Student("Chloe", 91)]
print(sorted(group))
print(min(group))[Student('Ben', 74), Student('Asha', 82), Student('Chloe', 91)]
Student('Ben', 74)One caution: a class that defines __eq__ and does not define __hash__ becomes unhashable, so you cannot put its objects in sets or use them as dictionary keys. That is the right behaviour for objects that can change, and a common surprise.
Size and membership: __len__ and __contains__
A container-like class can support len() and the in operator:
class Shelf:
def __init__(self):
self.books = []
def add(self, title):
self.books.append(title)
def __len__(self):
return len(self.books)
def __contains__(self, title):
return title in self.books
shelf = Shelf()
shelf.add("Night Trains")
shelf.add("The Silent Garden")
print(len(shelf))
print("Night Trains" in shelf)
print("Missing Book" in shelf)2
True
FalseArithmetic: __add__
You can give + a meaning for your own type. Here two money amounts add up and return a new Money object:
class Money:
def __init__(self, cents):
self.cents = cents
def __add__(self, other):
return Money(self.cents + other.cents)
def __str__(self):
return f"{self.cents // 100}.{self.cents % 100:02d}"
total = Money(250) + Money(175)
print(total)4.25Similar methods exist for - (__sub__), * (__mul__) and others. Use them only where the operator is natural: adding money is clear, but "adding" two customers is not.
Other useful ones
__getitem__ makes obj[0] work, __iter__ makes a loop over the object work, __bool__ controls truthiness, and __call__ makes an object callable like a function. You will meet some of these again in the generators lesson.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Returning the wrong type.
__str__must return a string, and__len__an integer. Otherwise Python raisesTypeError. - Printing inside
__str__instead of returning. The method should return text and leave printing to the caller. - Assuming
__eq__gives you sorting. Sorting needs__lt__. - Calling dunder methods directly. Write
a + b, nota.__add__(b). - Comparing with an object of another type.
other.xfails ifotheris not a point. For serious code, check the type first and returnNotImplementedwhen it does not match.
Exercise
Write a class Temperature that stores degrees. Give it a __repr__ such as Temperature(21), an __eq__ that compares degrees, and an __add__ that returns a new Temperature with the sum. Add two temperatures, print the result and print whether Temperature(5) == Temperature(5).
Show one possible answer
class Temperature:
def __init__(self, degrees):
self.degrees = degrees
def __repr__(self):
return f"Temperature({self.degrees})"
def __eq__(self, other):
return self.degrees == other.degrees
def __add__(self, other):
return Temperature(self.degrees + other.degrees)
print(Temperature(20) + Temperature(1))
print(Temperature(5) == Temperature(5))Temperature(21)
TrueKey points
- Special methods have double underscores on both sides, such as __str__, and Python calls them for you in response to syntax and built-in functions.
- __str__ controls print() and str(), while __repr__ gives an unambiguous form for developers.
- __eq__ defines ==, and __lt__ lets objects be compared and sorted.
- __len__ makes len() work, and __add__ makes + work.
- You almost never call a special method by name. You use the syntax or function that triggers it.