在Python类中支持等价(“相等”)的优雅方法在编写自定义类时,通过==和!=运算符允许等效通常很重要。在Python中,这可以通过分别实现__eq__和__ne__特殊方法来实现。我发现这样做的最简单方法是以下方法:class Foo:
def __init__(self, item):
self.item = item def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__ else:
return False
def __ne__(self, other):
return not self.__eq__(other)你知道更优雅的做法吗?您是否知道使用上述比较方法的任何特殊缺点__dict__?注意:有点澄清 - 何时__eq__和__ne__未定义,您会发现此行为:>>> a = Foo(1)>>> b = Foo(1)>>> a is bFalse>>> a == bFalse也就是说,a == b评估是False因为它真的运行a is b,是对身份的测试(即“ a与...相同的对象b”)。当__eq__和__ne__定义,你会发现这种行为(这是一个我们后):>>> a = Foo(1)>>> b = Foo(1)>>> a is bFalse>>> a == bTrue
3 回答

Qyouu
TA贡献1786条经验 获得超11个赞
你需要小心继承:
>>> class Foo: def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False>>> class Bar(Foo):pass>>> b = Bar()>>> f = Foo()>>> f == bTrue>>> b == fFalse
更严格地检查类型,如下所示:
def __eq__(self, other): if type(other) is type(self): return self.__dict__ == other.__dict__ return False
除此之外,您的方法将正常工作,这就是特殊方法。

慕标5832272
TA贡献1966条经验 获得超4个赞
你描述的方式是我一直以来的方式。由于它完全是通用的,因此您可以始终将该功能分解为mixin类,并在需要该功能的类中继承它。
class CommonEqualityMixin(object): def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __ne__(self, other): return not self.__eq__(other)class Foo(CommonEqualityMixin): def __init__(self, item): self.item = item
添加回答
举报
0/150
提交
取消