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

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

在 python 中自定義 __delattr__

在 python 中自定義 __delattr__

繁星coding 2022-06-28 17:32:30
以下是有效的__delattr__方法嗎?class Item:    def __delattr__(self, attr):        if attr in self.__dict__:            print ('Deleting attribute: %s' % attr)            super().__delattr__(attr)        else:            print ('Already deleted this attribute!')具體來說,super()“實際刪除”屬性的正確方法是什么?并且是attr in self.__dict__檢查屬性是否在實例中的正確方法嗎?
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

super 會調用父類對應的方法,你可以在這里實現自己的特殊方法,不需要參考它的 super 實現。考慮以下:


class Item:

    def __delattr__(self, attr):

        try:

            print ('Deleting attribute: %s' % attr)

            del self.__dict__[attr]

        except KeyError:

            print ('Already deleted this attribute!')

測試類:


>>> i.test = 'a value'

>>> del i.test

Deleting attribute: test

>>> del i.test

Deleting attribute: test

Already deleted this attribute!


查看完整回答
反對 回復 2022-06-28
  • 1 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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