super() in python

super() in Python

super() function is crucial for creating efficient and maintainable code. This powerful tool allows you to call methods from a parent class in a child class, enabling code reusability and maintaining a clear inheritance hierarchy.

super() in python

Python super()

The super() function in Python is a built-in function that provides a way to call methods and access attributes from the parent class within a subclass. It is particularly useful when dealing with inheritance, as it allows you to extend the functionality of the parent class while retaining its methods and attributes.

Syntax:

The super() function is called with two arguments: the first argument is the subclass that wants to access the parent class, and the second argument is the instance of that subclass. Let’s understand it with an example:

Example:

Run
class Parent:
    def show(self):
        print("This is a Parent class")

class Child(Parent):
    def display(self):
        print("This is a Child class")

    def show(self):
        super().show() 

child = Child()
child.display()
child.show()

Output : 

This is the Child class
This is the Parent class

You can also pass additional arguments to the super() function when calling it within a method. This allows you to customize the behavior of the parent class’s method based on the needs of the child class.

Advantages of super()

  • Code Reusability: super() promotes the reuse of code by allowing you to access and modify the behavior of parent class methods.
  • Maintainability: Inheritance hierarchies become more transparent, making code easier to maintain.
  • Consistency: super() ensures that the parent class’s methods are consistently invoked, even in complex inheritance structures.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription