如何在Python中对对象进行深度比较

2 投票
3 回答
6733 浏览
提问于 2025-04-17 21:49

有没有什么函数可以让我这样做呢?

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类的不同实例。

3 个回答

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)
1
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
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

如果你想要比较一些没有 __dict__ 属性的对象(比如用 C 定义的对象或者使用 __slots__ 的对象),你可以先用 hasattr 来检查这个属性是否存在:

return hasattr(other, '__dict__') and self.__dict__ == other.__dict__

或者你也可以使用 getattr 来安全地访问这个属性,并设置一个默认值:

return self.__dict__ == getattr(other, '__dict__', None)

撰写回答