Python super()

Python super() builtin function is used to get a proxy object that delegates method calls to a parent or sub class of specified type.

In this tutorial, we will learn about the syntax of Python super() function, and learn how to use this function with the help of examples.

Syntax

The syntax of super() function is

super([type[, object-or-type]])

where

ParameterRequired/OptionalDescription
typeOptionalType. For example class name. Parent of sibling class of this type is considered for delegating the method calls.
object-or-typeOptionalObject or Type. For example class name of object instance. This determines the method resolution order to be searched.

Example

In this example, we define two classes: A and B; where A is the super class for B. And in each of these classes we defined a method with same name: printMsg().

When we create an instance for class B and call printMsg() method on this instance, it would execute the method of class B. But if we would like to execute the method printMsg() of B’s super class, then we can use super() function, as shown in the following example.

Python Program

class A:
    def printMsg(self):
        print('Hello A')
        
class B(A):
    def printMsg(self):
        print('Hello B')

b = B()
b.printMsg()
super(B, b).printMsg()
Try Online

Output

Hello B
Hello A

Conclusion

In this Python Tutorial, we have learnt the syntax of Python super() builtin function, and also learned how to use this function, with the help of Python example programs.