search

What is the use of the "super" function in Python?

The **super** function in Python is used to refer to the parent class. It is commonly used in inheritance, when a subclass needs to override a method of its parent class but still wants to retain access to the parent method. The **super** function returns a temporary object of the superclass, which allows you to call its methods.

For example, consider the following code:

class Parent:
    def foo(self):
        print("Parent's foo")

class Child(Parent):
    def foo(self):
        print("Child's foo")
        super().foo()

c = Child()
c.foo()

The output of the above code will be:

Child's foo
Parent's foo

Here, **Child** overrides the **foo** method of its parent class **Parent**, but still calls the parent method using **super().foo()**. The **super** function is used to refer to the parent class, and the call to **super().foo()** invokes the parent method.

Related Questions You Might Be Interested