In Python multiple inheritance, take advantage of super (). The parent class method, you can call all the parent classes, so that in the state of the override, the call to all the parent class again!
Cases:
Print"****** multiple inheritance using super (). __init__ occurrence state ******")ClassParent(object):Def__init__(Self, name, *args, **kwargs):# to avoid multiple inheritance errors, use variable length parameters, accept the parameter print (' The init of the parent ' begins to be called ') Self.name = name Print (' Parent's init end is called ')ClassSon1(Parent):Def__init__(Self, name, age, *args, **kwargs):# to avoid multiple inheritance errors, use variable length parameters, accept the parameter print (' Son1 Init started being called ') Self.age = Age super (). __INIT__ (name, *args, **kwargs)# to avoid multiple inheritance errors, use variable length parameters, accept the parameter print (' Son1 init end is called ')ClassSon2(Parent):Def__init__(Self, name, gender, *args, **kwargs):# to avoid multiple inheritance errors, use variable length parameters, accept the parameter print (# to avoid multiple inheritance error, use variable length parameters, accept the parameter print (class grandson (Son1, Son2): def __init__ # multiple inheritance, relative to the use of the class name. __init__ method, to write all of the parent class once # and super only in a word, executed all the parent class method, This is one reason why multiple inheritance requires all of the arguments # super (grandson, self). __INIT__ (name, age, gender) super (). __INIT__ ( Name, age, gender) print (init end of grandson called ') print (grandson.__mro__)
#利用
.__mro__ method query super in multiple inheritance calls the order of the parent class
gs = grandson ( ' grandson ', 12, " print ( ' name: ', gs.name) print ( ' Age: ', gs.age) Print ( Gender: ', Gs.gender) print ( "****** multiple inheritance using super ()." __init__ Occurrence status ******\n\n ")
Operation Result:
******多继承使用super().__init__ 发生的状态******(<class ‘__main__.Grandson‘>, <class ‘__main__.Son1‘>, <class ‘__main__.Son2‘>, <class ‘__main__.Parent‘>, <class ‘object‘>)Grandson的init开始被调用Son1的init开始被调用Son2的init开始被调用parent的init开始被调用parent的init结束被调用Son2的init结束被调用Son1的init结束被调用Grandson的init结束被调用姓名: grandson年龄: 12性别: 男******多继承使用super().__init__ 发生的状态******
How super calls all parent classes in the Python language and the MRO order to be used