Python Func Super
# Python2.x Python super() Function
[ Python Built-in Functions](#)
* * *
## Description
The **super()** function is used to call a method of the parent (super) class.
**super()** is designed to solve multiple inheritance issues. Calling parent class methods directly using the class name works fine with single inheritance, but with multiple inheritance, it can lead to problems like lookup order (MRO) and repeated calls (diamond inheritance).
MRO stands for Method Resolution Order, which is essentially the order in which parent class methods are inherited.
### Syntax
Here is the syntax for the super() method:
super(type[, object-or-type])
### Parameters
* type -- The class.
* object-or-type -- The class, typically `self`.
One difference between Python 3.x and Python 2.x is: Python 3 allows you to use `super().xxx` directly instead of `super(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): # Remember to inherit object in Python2.x 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 demonstrates an example 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 (which is FooParent), then converts the FooChild object to a FooParent object 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:
ParentChildHelloWorld from ParentChild bar fuction I'm the parent.
[ Python Built-in Functions](#)
YouTip