0

I am trying to compare two class objects with == operator which gives me a 'False' even though the object.dict are same. for the code given below:-

class Item:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

cat_1 = Item('Cat', 5)
cat_2 = Item('Cat', 5)

print('id of cat1 ', id(cat_1))
print('id of cat2 ', id(cat_2))

print(cat_1 == cat_2 ) # why does it print return false as __dict__ is same?

Now if i add a ___eq____ function in my class:

class Item:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def __eq__(self, other):    # condition is given below
        if isinstance(other, Item) and other.weight == self.weight and other.name == self.name:
            return True
        else:
            return False

cat_1 = Item('Cat', 5)
cat_2 = Item('Cat', 5)

print('id of cat1 ', id(cat_1))
print('id of cat2 ', id(cat_2))

print(cat_1 == cat_2 ) # why does it print return True now?
print(cat_1.__eq__(cat2))

why does it return false in case 1 and true after i added eq method?

lynxx
  • 544
  • 3
  • 18
  • 2
    Possible duplicate of [Elegant ways to support equivalence ("equality") in Python classes](https://stackoverflow.com/questions/390250/elegant-ways-to-support-equivalence-equality-in-python-classes) – n8sty Oct 19 '18 at 03:12
  • What does print(cat_1) and print(cat_2) return individually? – logos_164 Oct 19 '18 at 03:12

1 Answers1

0

If you don't define the __eq__ method in your class, it will inherit it from the Object class, which only compares objects by identity. That means it will only return True if you are comparing an object to itself.

a = Object()
b = a
c = Object()
print (a == a) #True, an obj is always equal to itself
print (a == b) #True, both a and b are references to the same object 
print (a == c) #False, they are both empty instances from Object. However, they are different instances, different objects.

Once you have declared the __eq__ method, that's the one being called when you use '=='. You make the rules of when two instances of your class are equal in that case.

Pablo Paglilla
  • 366
  • 2
  • 5