Super is used to solve multiple inheritance problems, calling the parent class directly with the class name is fine when using single inheritance, but if you use multiple inheritance, it involves finding order (MRO), repeating calls (Diamond inheritance), and so on. In short, the experience left by predecessors is: to maintain consistency. Either call the parent class all with the class name, or all use super, not half.
Ordinary inheritance
Code
[Python] View plain copy class fooparent (object): def __init__ (self): self.parent = ' i\ ' m the parent .' print ' Parent ' def bar (self,message): print message, ' from parent ' class foochild (fooparent): def __ Init__ (self): fooparent.__init__ (self) print ' child ' def bar (self,message): fooparent.bar (self,message) print ' Child bar function. ' print self.parent if __name__== ' __main__ ': foochild = foochild () foochild.bar (' HelloWorld ')
Super inheritance
Code
[Python] View plain copy class fooparent (object): def __init__ (self): self.parent = ' i\ ' m the parent .' print ' Parent ' def bar (self,message): print message, ' from parent ' class foochild ( fooparent): def __init__ (self): super (foochild,self). __init__ () print ' child ' def bar (self,message): super ( Foochild, self). Bar (message) print ' Child bar fuction ' print self.parent if __name__ == ' __main__ ': fooChild = Foochild () foochild.bar (' HelloWorld ')
The program runs the same result: Parent
Child
HelloWorld from Parent
Child Bar Fuction
I ' m the parent.
From the results of the run, normal inheritance and super inheritance are the same. But in fact their internal operating mechanism is different, which is evident in multiple inheritance. In the super mechanism, the public parent class is guaranteed to be executed only once, and the order of execution is performed according to the MRO (e.__mro__).
Note that super inheritance can only be used in new classes, and when used for classic classes, an error occurs.
New class: Must have inherited classes, if there is nothing to inherit, then inherit the object
Classic class: There is no parent class, and if you call super at this point, an error occurs: "super () argument 1 must be type, not Classobj"
A detailed study of super usage can be referred to "http://blog.csdn.net/johnsonguo/article/details/585193"
Turn from: http://blog.csdn.net/lqhbupt/article/details/19631991