#栗子12-1 The __init__ and __update__ methods of the built-in type Dict ignore the __setitem__ we cover
Class Doppeldict (Dict):
def __setitem__ (self, Key, value):
Super (). __setitem__ (key,[value]*2)
DD = doppeldict (one=1)
Print (dd) #{' one ': 1}
Dd[' both '] = 2
Print (dd) #{' one ': 1, ' both ': [2, 2]}
Dd.update (three=3)
Print (dd) #{' one ': 1, ' both ': [2, 2], ' Three ': 3}
#不只实例内部的调用有这个问题 (Self.get () does not call self.__getitem__ ()), the method of the built-in type method calls the methods of other classes, and is not called if overridden.
The #栗子12-2 Dict.update method ignores the Answerdict.__getitem__ method
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[' both '] = 2
Print (dd) #{' one ': [1, 1], ' both ': [2, 2]}
Dd.update (three=3)
Print (dd) #{' one ': [1, 1], ' both ': [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}
# "Summary"
‘‘‘
In summary, the problems described in this section only occur on method delegates inside the built-in types implemented by the C language, and only affect
Directly inherits the user-defined class of the built-in type. If subclasses write classes using Python (collections modules), such as UserDict or
Mutablemapping, you won't be affected by this.
‘‘‘
#12.2 Multiple inheritance and method parsing order
#规则: According to the Order of __mro__ (method parsing), if you call the method directly with the class name to find the class directly, it is recommended to use super () [because it is safest and not easy to go out of date. ]
Print (bool.__mro__) # (<class ' bool ';, <class ' int ';, <class ' object ' >)
"Python" "Inherit"