This article mainly introduces the usage examples of super in Python, this article compares the general inheritance with the super inheritance, from the results of the run, ordinary inheritance and super inheritance are the same, but in fact their internal operating mechanism is different, this point in multiple inheritance is evident, Need friends can refer to the following
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
The code is as follows:
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
The code is as follows:
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:
The code is as follows:
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"