Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am having a class named as MyClass, that includes two member variables foo and bar:

class MyClass:

    def __init__(self, foo, bar):

        self.foo = foo

        self.bar = bar

I have two objects of this class, each of which has identical values for foo and bar:

x = MyClass('foo', 'bar')

y = MyClass('foo', 'bar')

But, when I compare them for equality, Python returns False:

>>> x == y

False

How can I make python acknowledge these two objects equal?

1 Answer

0 votes
by (108k points)

First of all, you have to implement the __eq__() fucntion:

class MyClass:

    def __init__(self, foo, bar):

        self.foo = foo

        self.bar = bar

    def __eq__(self, other): 

        if not isinstance(other, MyClass):

            # don't attempt to compare against unrelated types

            return NotImplemented

        return self.foo == other.foo and self.bar == other.bar

Now it outputs:

>>> x == y

True

Note that implementing __eq__ will automatically make objects of your class unhashable, which means they can't be collected in sets and dicts. If you're not modeling an immutable type then it's recommended to just leave your instances as unhashable.

If you are modeling an immutable type, you should also implement the data model hook __hash__:

class MyClass:

    ...

    def __hash__(self):

        # necessary for instances to behave sanely in dictionary and sets.

        return hash((self.foo, self.bar))

You can loop through the __dict__() and comparing values, is not advisable - it can never be truly general because the __dict__ may have un-comparable or un-hashable types contained within.

Want to become a Python Developer? Check out this insightful Python Certification course.

Related questions

0 votes
4 answers
asked Apr 1, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 11, 2019 in Python by ParasSharma1 (19k points)
0 votes
1 answer

Browse Categories

...