Scripting

Python super() Function

Python super() Function

Introduction

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. The following article is a detailed guide on how to use the super() function in Python as we go through the section below.

Example

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")

Output:

Dog can’t fly

Dog is an Animal

Definition

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.

The syntax

super ()

The benefits of super() function

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:

1. super() function references the class and its methods.

2. The arguments must match.

3. Must use super() after each method occurrence.

Conclusion

We have shown you how to use the super() function in detail in Python.

Thank you for reading.

Similar Posts