Python super() Function

Python 内置函数Python Built-in Functions


Description

super()The function is used to call a method of the parent class (superclass).

super()It is used to solve multiple inheritance problems. Calling a parent class method directly with the class name is fine for single inheritance, but with multiple inheritance, it involves various issues such as method resolution order (MRO), repeated calls (diamond inheritance), etc.

MRO is the method resolution order table of a class, which is actually the order table used when inheriting parent class methods.

Syntax

The following is the syntax of the super() method:

super(type[, object-or-type])

Parameters

  • type -- class.
  • object-or-type -- class, usually self

One difference between Python3.x and Python2.x is: Python 3 can directly usesuper().xxxinstead ofsuper(Class, self).xxx :

Python3.x Example:

class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3

Python2.x Example:

#!/usr/bin/python # -*- coding: UTF-8 -*- class A(object): # Python2.x remember to inherit object def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super(B, self).add(x) b = B() b.add(2) # 3

Return Value

None.


Example

The following shows an example of using the super function:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __init__(self): # super(FooChild,self) first finds the parent class of FooChild (that is class FooParent), then converts the object of class FooChild to an object of class FooParent 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')

Execution result:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

Python 内置函数Python Built-in Functions

Other Extensions