如何在python中对对象进行深度优化

时间:2014-03-11 17:53:45

标签: python object deepequals

是否有功能以便我可以

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

但是,默认情况下,它始终为false,因为x和y是Test

的不同实例

3 个答案:

答案 0 :(得分:1)

您可以实施__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

答案 1 :(得分:0)

您可能希望实施班级的__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)

答案 2 :(得分:0)

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