The super()
function in Python is used to call a method from a parent class. It is especially useful in the context of inheritance, as it allows you to access and extend the functionality of the parent class without explicitly naming it.
The super()
function is often used to call the parent class's constructor or methods. Here's an example:
class Parent: def display(self): return "This is the Parent class" class Child(Parent): def display(self): parent_message = super().display() return f"{parent_message} and this is the Child class" # Example usage child = Child() print(child.display()) # Output: This is the Parent class and this is the Child class
The super()
function is frequently used to initialize the parent class's constructor in the subclass.
class Parent: def __init__(self, name): self.name = name class Child(Parent): def __init__(self, name, age): super().__init__(name) self.age = age # Example usage child = Child("John", 12) print(child.name) # Output: John print(child.age) # Output: 12
When multiple inheritance is involved, super()
ensures that the methods of all parent classes are called in the correct order.
class ClassA: def show(self): return "ClassA method" class ClassB(ClassA): def show(self): parent_message = super().show() return f"{parent_message} and ClassB method" class ClassC(ClassB): def show(self): parent_message = super().show() return f"{parent_message} and ClassC method" # Example usage obj = ClassC() print(obj.show()) # Output: ClassA method and ClassB method and ClassC method
The super()
function is a vital tool in Python's object-oriented programming. It enables you to work with inheritance effectively, ensuring that the parent class's methods and constructors are called correctly while keeping the code clean and easy to maintain.