The super() function is used to call methods of a parent class. When a subclass overrides a method of its parent class, and you want to call the parent class's method within the subclass, you can use the super() function. Using super() helps avoid hardcoding the parent class's name, making the code more readable and maintainable.

Function Syntax

# Python 3 simplified syntax
super()
# Full syntax for Python 2/3 compatibility
super(type, object_or_type)

Full syntax parameters:

  • type: The current class.
  • object-or-type: The current instance or the current class.

super() returns a special proxy object that knows how to call methods of the parent class.

Examples of the super() Function

A simple example:

class Parent:
    def method(self):
        print("Parent.method")

class Child(Parent):
    def method(self):
        # Hardcoded call to parent class method
        Parent.method(self)
        # Simplified super method (most common)
        super().method()
        # Full super method
        super(Child,self).method()

        print("Child.method")

obj = Child()
obj.method()

Commonly used for initialization:

class Parent:
    def __init__(self):
        print("Parent __init__")

class Child(Parent):
    def __init__(self):
        super().__init__()
        print("Child __init__")

obj = Child()