Python, properly · Chapter 27 of 42
Dunder methods
By the end of this chapter you can make your own objects print clearly, compare with == and <, go in sets and dictionaries, add with +, and work with len, for and in, like Python's own types. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Objects
- 3 tasks
- Python
- In the all labs plan
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.
Why you need this
DabbaDrop's delivery slots are objects now, and Farah asked for the day's slots printed in order. Here is what a plain class gives her:
class Slot:
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
a = Slot(12, 30)
print(a)
print(a == Slot(12, 30))
print(sorted([Slot(13, 0), a]))
<__main__.Slot object at 0xffffb5a92900>
False
Traceback (most recent call last):
File "/workspace/chapters/27-dunder-methods/plain.py", line 10, in <module>
print(sorted([Slot(13, 0), a]))
~~~~~~^^^^^^^^^^^^^^^^^^
TypeError: '<' not supported between instances of 'Slot' and 'Slot'
An address, False for the same time, and no sorting. Strings, numbers and lists do all of this because their classes define special methods. Kunal: your classes can define the very same ones.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
rupees.py: money that prints and adds like money
Write a class Rupees. Rupees(amount) keeps the amount in the attribute amount. repr(Rupees(240)) is "Rupees(240)", while str() and print show "Rs 240".
Rupees(240) + Rupees(150) gives a new Rupees with amount 390 and leaves both unchanged. Adding anything that is not a Rupees (5, "5", 2.5) raises TypeError, and sum([Rupees(10), Rupees(20), Rupees(5)], Rupees(0)) gives a Rupees of 35.
- Task 2
order.py: an order that works with len, for and in
Write a class Order. Order(order_id, items) keeps order_id and items, a dictionary from dish id to quantity.
len(order) is the total quantity, looping over it gives the dish ids in the dictionary's order (every time it is looped over), "chole" in order says whether that dish id is in it, and repr(order) is "Order('D0042', 7 pieces)" for order D0042 with 7 pieces.
For Order("D0042", {"roti": 4, "chole": 2, "gulab-jamun": 1}): len is 7, the loop gives roti, chole, gulab-jamun, and "naan" in it is False. An empty order has length 0, is false, and shows as "Order('D0043', 0 pieces)".
- Task 3 · interview question
Interview: dish.py, __eq__ and __hash__ together
Write a class Dish. Dish(name, price) keeps both; repr(Dish("Roti", 15)) is "Dish('Roti', 15)".
Two dishes are equal when name and price are both equal, and a Dish compared with a non-Dish (like "Roti") is simply not equal, with no error. Equal dishes have equal hashes, so a set of Roti, Roti and Chole holds 2, and a dictionary with Dish("Chole", 150) as a key finds a new Dish("Chole", 150).
Dishes sort by price, then by name for the same price, and <=, > and >= all work.
What you will learn
- Dunder methods (double underscore, like __len__): what Python calls for print, ==, <, +, len, for and in.
- __repr__ for developers and __str__ for users.
- __eq__ and __hash__ together, and why one without the other breaks sets.
- NotImplemented: saying "I cannot do that" the right way.
More in Objects
Build "Dunder methods" yourself
DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.