標籤: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】【繼承】