gpt4 book ai didi

python - 使用 __dict__ 比较两个对象

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:36 26 4
gpt4 key购买 nike

有没有理由不这样做来比较两个对象:

def __eq__(self, other):
return self.__dict__ == other.__dict__

与检查每个单独的属性相反:

def __eq__(self, other):
return self.get_a() == other.get_a() and self.get_b() == other.get_b() and ...

最初我使用的是后者,但我认为前者是更清洁的解决方案。

最佳答案

你可以明确而简洁:

def __eq__(self, other):
fetcher = operator.attrgetter("a", "b", "c", "d")
try:
return self is other or fetcher(self) == fetcher(other)
except AttributeError:
return False

只需比较 __dict__ 属性(如果使用 __slots__ 则可能不存在)会让您面临对象上存在意外属性的风险:

class A:
def __init__(self, a):
self.a = a
def __eq__(self, other):
return self.__dict__ == other.__dict__

a1 = A(5)
a2 = A(5)
a1.b = 3
assert a1 == a2 # Fails

关于python - 使用 __dict__ 比较两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49948412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com