7

I have a class MyClass, which contains two member variables foo and bar:

class MyClass:
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

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

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

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

>>> x == y
False

How can I make python consider these two objects equal?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Ivy
  • 3,393
  • 11
  • 33
  • 46

2 Answers2

11

you have to tell python how exactly you want equality be defined. do so by defining a special method __eq__ like this:

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

the __cmp__(self, other) is the "old" style to compare instances of classes, and only used when there is no rich comparison special method found. read up on them here: http://docs.python.org/release/2.7/reference/datamodel.html#specialnames

ch3ka
  • 11,792
  • 4
  • 31
  • 28
7

The standard protocol is to define __cmp__() or __eq__() and __ne__().

If you don't, Python uses object identity ("address") to compare objects.

NPE
  • 486,780
  • 108
  • 951
  • 1,012