← All lessons

__eq__: when objects are equal

Sign in · Sign up

Lesson 10.10

By default == compares references: two objects with the same data are not equal. The __eq__ method sets your own rule:

class Hero:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp

    def __eq__(self, other):
        return self.name == other.name and self.hp == other.hp

print(Hero("Mia", 100) == Hero("Mia", 100))
  • self is this object, other is the one on the right of ==;
  • __eq__ returns True or False, not a number or a field value;
  • and is needed when equality depends on more than one field.

The check gives two pairs of "name and HP". Create two heroes and print whether they are equal.

Hint

__eq__ receives the second object as the parameter other and returns True/False.

Compare all the fields that make a hero "the same one" — here the name and the HP, both with and. Comparing one field would give True for different heroes.