__eq__Easy Examples

Defines behavior for the == equality operator

Implementing __eq__

Basic implementation of __eq__ in a class.

python
class Card:
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __eq__(self, other):
        return self.rank == other.rank and self.suit == other.suit

c1 = Card("A", "spades")
c2 = Card("A", "spades")
c3 = Card("K", "hearts")
print(c1 == c2)
print(c1 == c3)

__eq__ defines behavior for the == equality operator. Implementing it lets you customize how Python interacts with your objects.

__eq__ in action

Seeing __eq__ called by Python's built-in operations.

python
# How Python calls __eq__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        print(f"__eq__ was called!")
        return self

d = Demo(42)
# This triggers __eq__:
print(d == Demo(42))

Python automatically calls __eq__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground