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?