Start learning free

LESSON 608 OF 635 · OBJECT-ORIENTED PROGRAMMING

Comparing Objects in Python in Python

Lesson

TL ; DR:

By default, == asks if two names hold the very same object. Write __eq__ to compare the values instead. Write __hash__ too, so sets and dictionaries can find equal objects.


class Time:
    ...
    def __eq__(self, other):
        return self.hour == other.hour and self.minute == other.minute

    def __hash__(self):
        return hash((self.hour, self.minute))


Full lesson:

Two objects can hold the same values and still be two objects.

a = Time(9, 30)
b = Time(9, 30)
print(a == b)    # False

By default, == checks identity. It is True only when both names hold one and the same object. Here there are two objects, so it is False.

Equal by value

Usually you mean something else. Two times are equal when the hour and the minute match.

A class says this with __eq__(self, other). Python calls it for a == b, with a as self. It returns True when the fields match.

Sets need a hash

A set doesn't compare a new item with every item it holds. That would be slow. It files each object under a number, its hash. Then it compares only objects with the same hash.

So equal objects must have equal hashes. __hash__ returns that number. Build it from the same fields as __eq__. Here, hash((self.hour, self.minute)) hashes a tuple of both fields.

Write both

Python has a safety rule. A class with __eq__ but no __hash__ can't go in a set. Python raises a TypeError instead.


Your task

The Time class keeps an hour and a minute. Give it __eq__ and __hash__. Two times are equal when the hour and the minute both match.

The code below the class compares three times. Then it puts them in a set of alarms.

Expected output:

a and b are the same time
a and c are different times
alarms: 2
STEP 1 OF 2
    Ctrl + Enter to check

    Comparing Objects in Python

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free