我已经定义了一个类:
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
?
答案 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