我有一个类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认为这两个对象相等?
重写对象中的富比较运算符。
class MyClass:
def __lt__(self, other):
# return comparison
def __le__(self, other):
# return comparison
def __eq__(self, other):
# return comparison
def __ne__(self, other):
# return comparison
def __gt__(self, other):
# return comparison
def __ge__(self, other):
# return comparison
是这样的:
def __eq__(self, other):
return self._id == other._id
你应该实现方法__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