Lesson 2 · Unit 01
The data model
Operators are methods: equality, hashing, repr and friends
What you practise
__repr__,__eq__and__hash__,__len__and__getitem__, operators as methods- A class that behaves like a built-in
dataclassfor the boilerplate
Try a question from this lesson
Pick one
Two points with the same coordinates. What prints?
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
a = Point(1, 2)
b = Point(1, 2)
print(a == b, a in [b])Hint
The class never says what "equal" means. What is left to compare?
Correct answer
False False
Why
A class that does not define equality inherits it from object, where == means "same object". Two separate points are never equal that way, and in relies on ==, so it fails too.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Operators are method calls
Syntax is translated into methods with double underscores, looked up on the class.
Define the method and your objects work with the operator, the built-in or the statement, exactly like the built-in types do.
a == b # a.__eq__(b)
len(x) # x.__len__()
x[i] # x.__getitem__(i)
a + b # a.__add__(b)
k in x # x.__contains__(k)
print(x) # x.__str__(), else __repr__()11 more exercises in the app
- 2× fill the blanks
- 3× multiple choice
- 4× type the answer
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.