亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python類中支持等價(“相等”)的優雅方法

在Python類中支持等價(“相等”)的優雅方法

喵喵時光機 2019-07-29 10:13:38
在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

除此之外,您的方法將正常工作,這就是特殊方法。


查看完整回答
反對 回復 2019-07-29
?
慕標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


查看完整回答
反對 回復 2019-07-29
  • 3 回答
  • 0 關注
  • 810 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號