在Python類中支持等價(“相等”)的優(yōu)雅方法在編寫自定義類時,通過==和!=運算符允許等效通常很重要。在Python中,這可以通過分別實現(xiàn)__eq__和__ne__特殊方法來實現(xiàn)。我發(fā)現(xiàn)這樣做的最簡單方法是以下方法: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)你知道更優(yōu)雅的做法嗎?您是否知道使用上述比較方法的任何特殊缺點__dict__?注意:有點澄清 - 何時__eq__和__ne__未定義,您會發(fā)現(xiàn)此行為:>>> a = Foo(1)>>> b = Foo(1)>>> a is bFalse>>> a == bFalse也就是說,a == b評估是False因為它真的運行a is b,是對身份的測試(即“ a與...相同的對象b”)。當__eq__和__ne__定義,你會發(fā)現(xiàn)這種行為(這是一個我們后):>>> a = Foo(1)>>> b = Foo(1)>>> a is bFalse>>> a == bTrue
3 回答

Qyouu
TA貢獻1786條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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
提交
取消