What is the purpose of the super() function in Python?

What is the purpose of the super() function in Python?

a) To call a method from a parent class in the child class
b) To create an instance of a superclass
c) To override a method in a parent class
d) To initialize class attributes

Answer:

a) To call a method from a parent class in the child class

Explanation:

The super() function in Python is used to call a method from a parent class in the child class. It is commonly used to extend or customize the behavior of inherited methods in the child class while still retaining the functionality provided by the parent class.

class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        super().greet()  # Call the greet method of the Parent class
        print("Hello from Child")

# Creating an object of the Child class
child = Child()
child.greet()  # Output: Hello from Parent
               #         Hello from Child

In this example, the super() function is used in the Child class to call the greet() method of the Parent class. This allows the Child class to add its own behavior while still using the functionality of the parent class.

Using super() is important for ensuring that inherited methods are properly extended and that the parent class’s behavior is not unintentionally overridden or ignored.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top