Home » Learn Python » Dunder (Magic) Methods » Comparing Objects

Comparing Objects

If you want it to be possible to compare your objects using ==, you can implement __eq__

The default implementation will only tell you if two variables refer to the same object, but by implementing __eq__ you can make it possible to check if two objects are equal semantically: in terms of their programmer-defined meaning.

class Clock:
    def __init__(self, time):
        self._time = time

    def __str__(self):
        return f"It's {self._time} o'clock"

    def __eq__(self, other):
        return self._time == other._time

    # Don't let the time get bigger than 12 (hours)
    def __add__(self, other):
        newtime = (self._time + other._time) % 12
        return Clock(newtime)

c1 = Clock(8)
c2 = Clock(7) 
c3 = Clock(8)

print(c1 == c2)
print(c2 == c3)
print(c1 == c3)

If we don’t implement __eq__ here, the three comparisons all return False, since none of the variables refer to the same object.

Less Than, Greater Than

In the same way, it’s possible to implement other logical operators like __lt__ (less than, <) or __gt__ (greater than, >) to make it possible to use these operators with your objects. They also return True or False.

See the Python docs for more information.

Leave a Reply

Blog at WordPress.com.