Answers for "why __eq__() used in python"

1

__eq__ python

# The __eq__ method of a class is called when using the == operator
# You can overload it for custom == logic

class Food:
    def __init__(self, name, price):
        self.name = name
        self.price = price

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

cheap_bread = Food('bread', 5)
expensive_bread = Food('bread', 1000)

print(cheap_bread == expensive_bread)
# True
Posted by: Guest on March-13-2021

Python Answers by Framework

Browse Popular Code Answers by Language