How to Use the Python super() Function

09/17/2021

Contents

In this article, you will learn how to use the Python super() function.

Python super() Function

The super() function in Python is used to call a method or attribute of a parent class from a subclass. It allows you to access the methods and attributes of the parent class that have been overridden or extended by the subclass. Here’s how to use the super() function in Python:

Call the superclass constructor in the subclass constructor:

If you want to call the constructor of the parent class from the constructor of the subclass, you can use the super() function. Here’s an example:

class ParentClass:
    def __init__(self, name):
        self.name = name

class ChildClass(ParentClass):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

In this example, the ChildClass inherits from ParentClass. In the constructor of ChildClass, we call the constructor of ParentClass using super().__init__(name) to initialize the name attribute of the parent class.

Call the superclass method in the subclass method:

If you want to call a method of the parent class from a method of the subclass, you can use the super() function. Here’s an example:

class ParentClass:
    def say_hello(self):
        print("Hello from ParentClass")

class ChildClass(ParentClass):
    def say_hello(self):
        super().say_hello()
        print("Hello from ChildClass")

In this example, ChildClass overrides the say_hello() method of ParentClass. In the say_hello() method of ChildClass, we call the say_hello() method of the parent class using super().say_hello(), and then print “Hello from ChildClass” to the console.

Note that the super() function returns a temporary object of the superclass, which allows you to call its methods and attributes.