【Python】【繼承】

來源:互聯網
上載者:User

標籤:c 語言   object   其他   sel   value   tab   item   get   自訂   

#栗子12-1 內建類型dict 的__init__和__update__方法會忽略我們覆蓋的__setitem__

class DoppelDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key,[value]*2)
dd = DoppelDict(one=1)
print(dd) #{‘one‘: 1}
dd[‘two‘] = 2
print(dd) #{‘one‘: 1, ‘two‘: [2, 2]}
dd.update(three=3)
print(dd) #{‘one‘: 1, ‘two‘: [2, 2], ‘three‘: 3}


#不只執行個體內部的調用有這個問題(self.get() 不調用 self.__getitem__()),內建類型的方法調用的其他類的方法,如果被覆蓋了,也不會被調用

#栗子12-2 dict.update方法會忽略AnswerDict.__getitem__方法
class AnswerDict(dict):
def __getitem__(self, item):
return 42
ad = AnswerDict(a=‘foo‘)
print(ad[‘a‘]) #42
d = {}
d.update(ad)
print(d[‘a‘]) #foo
print(d) #{‘a‘: ‘foo‘}


import collections

class DoppelDict2(collections.UserDict):
def __setitem__(self, key, value):
super().__setitem__(key,[value]*2)
dd = DoppelDict2(one=1)
print(dd) #{‘one‘: [1, 1]}
dd[‘two‘] = 2
print(dd) #{‘one‘: [1, 1], ‘two‘: [2, 2]}
dd.update(three=3)
print(dd) #{‘one‘: [1, 1], ‘two‘: [2, 2], ‘three‘: [3, 3]}
class AnswerDict2(collections.UserDict):
def __getitem__(self, item):
return 42
ad = AnswerDict2(a=‘foo‘)
print(ad[‘a‘]) #42
d = {}
d.update(ad)
print(d[‘a‘]) #42
print(d) #{‘a‘: 42}





#【小結】
‘‘‘
綜上,本節所述的問題只發生在 C 語言實現的內建類型內部的方法委託上,而且隻影響
直接繼承內建類型的使用者自訂類。如果子類化使用 Python 編寫的類(collections 模組),如 UserDict 或
MutableMapping,就不會受此影響
‘‘‘


#12.2 多重繼承和方法解析順序
#規則:按照__mro__(方法解析)順序,若直接用類名調用方法則直接找到該類,建議使用super()[因為最安全,也不容易過時。]
print(bool.__mro__) #(<class ‘bool‘>, <class ‘int‘>, <class ‘object‘>)

【Python】【繼承】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.