Python super() Function
Description
super() The function is used to call a method of a parent (super) class.
super() It is used to solve multiple inheritance problems. Calling a parent class method directly with the class name works fine with single inheritance, but with multiple inheritance it involves issues such as method resolution order (MRO), repeated calls (diamond inheritance), and so on.
MRO is the method resolution order list of a class, that is, the order in which parent class methods are inherited.
Syntax
The following is the syntax of the super() method:
super(type[, object-or-type])
Parameters
- type -- the class.
- object-or-type -- a class or object, usually self
One difference between Python 3.x and Python 2.x is: Python 3 can use super().xxx directly instead of super(Class, self).xxx:
Python 3.x example:
class
A
:
def
add
(
self
,
x
)
:
y
=
x
1
(
y
)
class
B
(
A
)
:
def
add
(
self
,
x
)
:
super
(
)
.
add
(
x
)
b
=
B
(
)
b
.
add
(
2
)
3
Python 2.x example:
#!/usr/bin/python
-- coding: UTF-8 --
class
A
(
object
)
:
In Python 2.x, remember to inherit object
def
add
(
self
,
x
)
:
y
=
x
1
(
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 examples demonstrate the use of the super function:
Example
#!/usr/bin/python
-- coding: UTF-8 --
class
FooParent
(
object
)
:
def
init
(
self
)
:
self
.
parent
=
'
I
'
m the parent.
'
(
'
Parent
'
)
def
bar
(
self
,
message
)
:
(
"
%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 into an object of class FooParent
super
(
FooChild
,
self
)
.
init
(
)
(
'
Child
'
)
def
bar
(
self
,
message
)
:
super
(
FooChild
,
self
)
.
bar
(
message
)
(
'
Child bar fuction
'
)
(
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 built-in function