第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

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

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


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


查看完整回答
反對 回復(fù) 2019-07-29
  • 3 回答
  • 0 關(guān)注
  • 805 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號