比较对象-在以下示例中,为什么==返回'False'?

时间:2018-10-19 02:54:37

标签: python python-3.x python-2.7

我正在尝试使用==运算符比较两个类对象,即使该对象相同,这也会给我一个'False'。 dict 。对于下面给出的代码:-

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?

现在,如果我在课堂上添加___eq____函数:

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))

为什么在情况1中返回false并在添加 eq 方法后返回true?

1 个答案:

答案 0 :(得分:0)

如果您未在类中定义__eq__方法,它将从Object类继承,该类仅按标识比较对象。这意味着只有在将对象与其自身进行比较时,它才会返回True。

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.

声明了__eq__方法后,即使用'=='时将调用该方法。在这种情况下,您要确定类的两个实例何时相等的规则。