有什么函数可以让我
class Test():
def __init__(self):
self.value_1 = 42
x = Test()
y = Test()
deepequals(x, y) == True
x.value = 7
deepequals(x, y) == False
y.value = 7
deepequals(x, y) == True但是,默认情况下,它总是错误的,因为x和y是不同的Test实例
发布于 2014-03-11 18:01:20
您可以实现__eq__ (等于)“魔术方法”:
class Test():
def __init__(self):
self.value_1 = 42
def __eq__(self, other):
return self.__dict__ == other.__dict__其中__dict__保存了所有实例属性。当两个对象对所有相同的属性都有相同的值时,这将返回True。这给出了您想要的结果:
>>> x = Test()
>>> y = Test()
>>> x == y
True
>>> x.value = 7
>>> x == y
False
>>> y.value = 7
>>> x == y
True若要支持与没有__dict__属性的对象(如C中定义的对象或使用__slots__ )的比较,可以首先使用hasattr检查该属性
return hasattr(other, '__dict__') and self.__dict__ == other.__dict__或者使用默认的getattr安全地访问它:
return self.__dict__ == getattr(other, '__dict__', None)发布于 2020-09-20 11:19:50
class Test:
def __init__(self):
self.value_1 = 42
def __eq__(self, other):
return (
self.__class__ == other.__class__ and
self.value_1 == other.value_1)
t1 = Test()
t2 = Test()
print(t1 == t2)输出
True发布于 2014-03-11 18:02:41
您可能希望实现类的__eq__。然后可以使用标准比较运算符:
class Test():
def __init__(self):
self.value = 42
def __eq__ (self, other):
return self.value == other.value
x = Test()
y = Test()
print (x == y)
x.value = 7
print (x == y)
y.value = 7
print (x == y)https://stackoverflow.com/questions/22332729
复制相似问题