Course 1.2Lesson 3 of 5
Special methods have names with two underscores on each side, and Python calls them for you when an object meets print, str, repr, equality, ordering, plus, minus, times, abs, len, in, indexing or truth. __str__ gives the text that print shows and __repr__ the text for programmers, which a list of objects shows. __eq__ says when two objects are equal, and without it two objects with the same values are different. __lt__ lets sorted, min and max put objects in order. __add__ and its relatives make operators work, __len__ and __contains__ make len and in work, and __getitem__ lets a loop go through the object. These make your objects feel like the built-in values.
Try the code and the simulations beside the lesson.
After this lesson you can
__str__ and __repr__,__eq__,sorted, min and max order your objects with __lt__, and+, len, in and loops work on your objects.You have seen __init__, which Python calls when an object is made. There are many more special methods, all with two underscores on each side. You do not call them yourself. Python calls them when an object meets a certain syntax.
When you write print(p), Python calls p.__str__(). When you write p1 == p2, it calls p1.__eq__(p2). When you write len(p), it calls p.__len__(). By writing these methods, you teach your objects how to behave like the built-in values.
Predict first. What does print(Plain(3)) show? Then run it.
__str__, print shows something like <__main__.Plain object at 0x7f...>: the class and a memory address. It tells a human nothing.__str__ returns the text that print and str() show. It is for users: friendly and short.__repr__ returns the text that the shell shows and that a list uses for its items. It is for programmers: unambiguous, and often looks like the code that makes the object. That is why print([Nice(1), Nice(2)]) shows Nice(x=1) in the list.__repr__, because print falls back to it when there is no __str__.Both must return a text. A common mistake is to print inside __str__ instead of returning.
A warning: if you write __eq__, a class stops being usable as a dictionary key or in a set unless you also write __hash__. That is a topic for later.
| You write | Python calls | Result here |
|---|---|---|
a + b | a.__add__(b) | a new basket with all the items |
len(both) | both.__len__() | the number of items |
"book" in both | both.__contains__("book") | True or False |
both[0] | both.__getitem__(0) | the first item |
for item in both | __getitem__ with 0, 1, 2, ... | each item in turn |
bool(basket), if basket: | __bool__ | True if not empty |
__add__ returns a new object. It does not change a or b. This is how + works for numbers and lists too.
The line for item in both works only because __getitem__ exists: Python tries positions 0, 1, 2, ... until it gets an IndexError. That is why __getitem__ was enough, without writing a loop method.
Python calls the special methods for you: + calls __add__, abs() calls __abs__, and print() uses __repr__ when there is no __str__.
__str__ that prints and does not return. print then shows None or an error.__eq__ that fails for another type. Money(5) == 5 raises an AttributeError. A careful __eq__ checks isinstance(other, Money) first.__add__. It should return a new one.__lt__ but expecting > to work. Python can try the other way round for >, but do not rely on it for every operator.__str or _str_ is just an ordinary method that nobody calls.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
__str__ and __eq__, and the checker tries them.__str__ is for print, __repr__ is for programmers and lists. Both return text.__eq__ defines ==. __lt__ lets sorted, min and max work.__add__, __len__, __contains__ and __getitem__ make +, len, in and loops work.__add__ returns a new object.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
print(p) call?Money(50) == Money(50) False without __eq__?sorted and min need?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.