在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
喵喵时光机
Qyouu
慕标5832272
随时随地看视频慕课网APP
相关分类