在编写自定义类时,通过==和!=运算符允许等效通常很重要.在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)
Run Code Online (Sandbox Code Playgroud)
你知道更优雅的做法吗?您是否知道使用上述比较方法的任何特殊缺点__dict__?
注意:有点澄清 - 何时__eq__和__ne__未定义,您会发现此行为:
>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
False
Run Code Online (Sandbox Code Playgroud)
也就是说,a == b评估是False因为它真的运行a is b,是对身份的测试(即" a与...相同的对象b"). …