Skip to main content

super()

The super() function is a built-in function in Python that returns a temporary object of the superclass (parent class) of the given object. It allows you to call methods of the superclass in a derived class, enabling multiple inheritance and cooperative multiple inheritance in Python.

Parameter Values

Parameter Description
type

The type to bind to.

obj

The object on which super() is called. Typically, this is a class.

Return Values

The super() function in Python returns a temporary object of the superclass.

How to Use super() in Python

Example 1:

The super() function is used to call a method from a parent class in Python. It returns a temporary object of the superclass that allows you to call methods defined in the superclass.

class Parent:
    def show(self):
        print('Parent class method')

class Child(Parent):
    def show(self):
        super().show()  # calling the Parent class method

obj = Child()
obj.show()
Example 2:

The super() function can also be used with multiple inheritances to call methods of all parent classes in a specific order.

class A:
    def show(self):
        print('A class method')

class B:
    def show(self):
        print('B class method')

class C(A, B):
    def show(self):
        super().show()

obj = C()
obj.show()
Example 3:

The super() function should be used carefully in multiple inheritance scenarios to ensure the correct method resolution order (MRO) is followed.

class X:
    def show(self):
        print('X class method')

class Y(X):
    def show(self):
        print('Y class method')

class Z(X):
    def show(self):
        super().show()

obj = Z()
obj.show()