在Python中(我使用的是v 3.4版本),可以像大多数其他语言一样使用
当比较基于类的对象时,Python会引用该类的
然而,执行以下示例代码:
this == that
来测试两个对象是否相等。当比较基于类的对象时,Python会引用该类的
__eq__
方法进行比较。然而,执行以下示例代码:
class Foo:
def __init__(self, bar):
self.bar = bar
one = Foo('text')
two = Foo('text')
调用one == two
会返回False
,因为Python只检查标识(identity),而不是数据相等性。
这导致你最终需要实现很多__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方法作为类对象的默认方法吗?
这种方法可能存在哪些负面影响?
__eq__
和__ne__
方法,并使其他类继承该基类,则无需在许多地方重复定义。 - unutbu