Sobes.tech
Junior — Middle

What is the purpose of implementing the __eq__ method in Python, and what tasks does it solve?

sobes.tech AI

Answer from AI

The __eq__ method in Python is used to define the behavior of the equality operator == between class objects. By default, object comparison is based on their identity (memory address), but often it is necessary to compare objects based on the values of their attributes.

By implementing __eq__, you specify the logic by which two objects are considered equal. This is important for the correct functioning of data structures such as sets (set) and dictionaries (dict), where key equality is checked.

Example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)  # True

Without __eq__, this code will return False because the objects are different by address.