Python Object Equality

I have a class MyClass that contains two member variables foo and bar.

I have two instances of this class, each of which has the same values ​​for foo and bar.

However, when I compare them for equality, Python returns False.

How can I guarantee that these objects are equal, without having to manually check the values ​​of their attributes every time they are compared? For example, I would like to be able to use the "in" operator.

+3
source share
2 answers

you have to tell python exactly how you want to define equality. do this by specifying a special method __eq__as follows:

def __eq__(self, other):
    return self.attrfoo == other.attrfoo # change that to your needs

__cmp__(self, other) - "" rich comparison. : http://docs.python.org/release/2.7/reference/datamodel.html#specialnames

+6

__cmp__() __eq__() __ne__().

, Python ( "" ) .

+5

All Articles