Skip to the content

Comparing objects

Python · Unit 14: Modern classes

Two different objects with the same data are not equal: == between objects asks whether they are the same object, not whether they look alike.

In a @dataclass it does compare the data, because the decorator also writes an __eq__ that goes field by field.

from dataclasses import dataclass

class Mug:
    def __init__(self, ml):
        self.ml = ml

@dataclass
class Glass:
    ml: int

print(Mug(250) == Mug(250))
print(Glass(250) == Glass(250))

Prints

False
True

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Complete the code

    Complete it so two chips with the same number are equal.

  4. 4. Find the bug

    Two grades with the same value should be equal, so it should print True. Which line has the error?

  5. 5. Predict the output

    Two students are the same one if they share a student number. What does it print?

  6. 6. Complete the code

    Complete it so it prints the title of the shortest book.

  7. 7. Find the bug

    It should print the name of the cheapest item, salt. Which line has the error?

  8. 8. Predict the output

    Ana and Leo are tied on points. What does it print?

  9. 9. Multiple choice

    In a @dataclass(order=True) with points and name, what changes if you write name before points?

  10. 10. Find the case that fails

    best(points) takes a list of scores and returns the highest one, or 0 if the list comes in empty. Which call breaks it?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →