gpt4 book ai didi

python - 出于好奇 : Why is python3 not using __dict__ compare as the default equality implementation?

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:49 24 4
gpt4 key购买 nike

在 Python 中(我使用的是 v 3.4),可以像在大多数其他语言中一样使用 this == that 来测试两个对象是否相等。

当比较基于类的对象时,python 引用类的__eq__方法进行比较。

但是,执行类似于以下示例的操作:

class Foo:
def __init__(self, bar):
self.bar = bar

one = Foo('text')
two = Foo('text')

调用 one == two 将产生 False,因为 python 只检查身份,而不检查数据是否相等。

这导致您最终实现了很多 __eq____ne__(不等于)方法,完全如下:

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

def __ne__(self, other):
return not self.__eq__(other)

为什么我们必须这样做?

有谁知道,为什么他们决定不将 dict-compare 方法实现为基于类的对象的默认方法?

这种方法的负面影响是什么?

最佳答案

Why do we have to do this?

因为显式优于隐式。

您假设实例完全基于它们的属性是相等的;这不一定是规则。以使用私有(private)属性跟踪缓存数据的类为例。而那些具有大量属性但不需要支持相等性的类呢?为什么他们需要支付额外的性能损失?

Python 没有做出这样的假设,而是要求您明确定义相等性。这还有一个额外的好处,即如果您不想希望支持实例之间的相等性,则您不需要再次禁用此类相等性测试。

对于简单的情况,可以使用 vars(self)self.__dict__,当然:

def __eq__(self, other):
if not isinstance(other, __class__):
return NotImplemented
return vars(self) == vars(other)

def __ne__(self, other):
if not isinstance(other, __class__):
return NotImplemented
return not self.__eq__(other)

返回 NotImplemented 确保其他对象也有机会实现相等性测试。

关于python - 出于好奇 : Why is python3 not using __dict__ compare as the default equality implementation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26641247/

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