__eq__

Dunder MethodPython 2.0+Intermediate

Defines behavior for the == equality operator

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

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.

Try in Playground

Tags

oopmagic-methodprotocolcore