Bitpath

Lesson 2 · Unit 01

The data model

Operators are methods: equality, hashing, repr and friends

13 exercisesabout 3 min

What you practise

  • __repr__, __eq__ and __hash__, __len__ and __getitem__, operators as methods
  • A class that behaves like a built-in
  • dataclass for the boilerplate

Try a question from this lesson

Pick one

Two points with the same coordinates. What prints?

Python
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?

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.

One email when Bitpath is ready to try. Nothing else. Privacy