Python - 比较2个相同的对象返回False?

时间:2016-10-21 20:37:16

标签: python equality

我已经定义了一个类:

class User:

    Name = ""
    Age = ""
    Gender = ""

    def __init__(self, var1, var2, var3):
        self.Name = var1
        self.Age = var2
        self.Gender = var3

    def __hash__(self):
        return hash(self.Name)

现在,当我创建两个相同的对象时:

User1 = User("Ted", "43", "M")
User2 = User("Ted", "43", "M")

并尝试比较它们:

print(User1 == User2)

它返回False

2 个答案:

答案 0 :(得分:6)

您需要覆盖__eq__方法:

def __eq__(self, other):
    if isinstance(other, User):
        return self.Name == other.Name and \
               self.Age == other.Age and \
               self.Gender == other.Gender
    return NotImplemented

答案 1 :(得分:2)

Mureinik提供的答案是正确的,但不完整。

在检查不等式时,仅覆盖__eq__方法会导致意外行为。

例如,只有User1 != User2被覆盖,True才会返回__eq__

您想同时定义__eq____ne__

def __eq__(self, other):
    if isinstance(other, User):
        return self.Name == other.Name and \
           self.Age == other.Age and \
           self.Gender == other.Gender
    return NotImplemented

def __ne__(self, other):
    return not self.__eq__(other)

现在,当您进行比较时,您将获得预期的结果:

User1 = User("Ted", "43", "M")
User2 = User("Ted", "43", "M")
print(User1 != User2)
print(User1 == User2)

打印:

False
True