Inheritance in Python is one of the important OOP features. Inheritance is understood as a class that inherits behavior from another class. The child class is the inheriting class of the parent class.
A superclass can be referenced to a subclass with the super() function. The super() function returns a proxy object, the method of the base class through delegation is a substitute object. This is called the indirect method (ability to reference a base object with super() function.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python methods queries.
In this context, we shall look into how to use the super() function in Python.
A temporary object of the superclass is returned by the super() function. Since this indirect reference method is only used at runtime, the base classes can be used at different times.
Its syntax is:
super ()
class Animal():
def __init__(self, name):
print(name, "is an Animal")
class fly(Animal):
def __init__(self, canFly_name):
print(canFly_name, "can't fly")
# Calling Parent class
# Constructor
super().__init__(canFly_name)
class Animal(fly):
def __init__(self, name):
# Calling the constructor
# of both thr parent
# class in the order of
# their inheritance
super().__init__(name)
d = Animal("Dog")
The Output will give:
Dog can't fly
Dog is an Animal
1. Access methods without having to remember or specify the superclass name. Can be used in one or more inheritance.
2. This implements modularity and code reuse.
* Note when using super() function:
i. super() function references the class and its methods.
ii. The arguments must match.
iii. Must use super() after each method occurrence.
This article covers how to use the super() function in Python. The super() builtin returns a proxy object (temporary object of the superclass) that allows us to access methods of the base class.