我有一个类MyClass,它包含两个成员变量foo和bar:
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
我有这个类的两个实例,每个实例都有相同的foo和bar值:
x = MyClass('foo', 'bar')
y = MyClass('foo', 'bar')
然而,当我比较它们是否相等时,Python返回False:
>>> x == y
False
我如何使python认为这两个对象相等?
你应该实现方法__eq__:
class MyClass:
def __init__(self, foo, bar, name):
self.foo = foo
self.bar = bar
self.name = name
def __eq__(self,other):
if not isinstance(other,MyClass):
return NotImplemented
else:
#string lists of all method names and properties of each of these objects
prop_names1 = list(self.__dict__)
prop_names2 = list(other.__dict__)
n = len(prop_names1) #number of properties
for i in range(n):
if getattr(self,prop_names1[i]) != getattr(other,prop_names2[i]):
return False
return True
如果你想逐个属性进行比较,并查看它是否以及在哪里失败,你可以使用下面的列表推导式:
[i for i,j in
zip([getattr(obj_1, attr) for attr in dir(obj_1)],
[getattr(obj_2, attr) for attr in dir(obj_2)])
if not i==j]
这里的额外优势是,当在PyCharm中调试时,您可以压缩一行并在“Evaluate Expression”窗口中输入。