How to Call a Parent class method in Python ?


In object-oriented programming, inheritance allows you to create new classes based on existing ones, providing a way to reuse code and organize your program's structure. Python, being an object-oriented language, supports inheritance and allows you to override methods defined in parent classes in child classes. However, there may be situations where you want to leverage the functionality of a parent class method while extending or modifying it in the child class.

Method Overriding in Python

Before we learn about calling parent class methods, let's briefly discuss method overriding. Method overriding is a feature in object-oriented programming that allows a subclass to provide a different implementation of a method that is already defined in its parent class. When you override a method, you redefine it in the subclass with the same name as in the parent class.

To illustrate method overriding in Python, consider the following example −

class ParentClass:
   def my_method(self):
      print("This is the parent class method.")

class ChildClass(ParentClass):
   def my_method(self):
      print("This is the child class method.")

In the code snippet above, we have a ParentClass with a method called my_method(). The ChildClass inherits from ParentClass and also defines its own my_method().

When you create instances of these classes and call the my_method() on them, Python uses the implementation defined in the respective classes 

parent = ParentClass()
child = ChildClass()

parent.my_method()  # Output: "This is the parent class method."
child.my_method()  # Output: "This is the child class method."

As you can see, calling my_method() on an instance of ParentClass invokes the parent class implementation, while calling it on an instance of ChildClass invokes the overridden method in the child class.

Calling the Parent Class Method

In Python, you can call the parent class method from within the overridden method using the super() function. The super() function returns a temporary object of the parent class, allowing you to access its methods.

The general syntax for calling a parent class method using super() is as follows 

class ChildClass(ParentClass):
   def overridden_method(self):
      super().method_name(arguments)
      # Additional code in the child class method

Here's an example that demonstrates how to call the parent class method using super() −

class ParentClass:
   def my_method(self):
      print("This is the parent class method.")

class ChildClass(ParentClass):
   def my_method(self):
      super().my_method()  # Calling the parent class method
      print("This is the child class method.")

In the above example, the ChildClass overrides the my_method() defined in the ParentClass. Inside the overridden method of the child class, we use super().my_method() to call the parent class method. This ensures that the parent class method is executed before the additional code in the child class method.

When you create an instance of the ChildClass and call the my_method(), both the parent class method and the child class method will be invoked 

child = ChildClass()
child.my_method()

# Output:
# "This is the parent class method."
# "This is the child class method."

As you can see, the super().my_method() call within the child class method invokes the parent class method first, followed by the execution of the child class method.

By calling the parent class method using super(), you can effectively extend or modify the behavior of the parent class method while retaining its original functionality. This approach is particularly useful when you want to add additional processing or customize certain aspects of the parent class method.

Benefits of Using super() to Call Parent Class Methods

Using the super() function to call parent class methods offers several benefits in the context of object-oriented programming. Let's explore some of these advantages 

Code Reusability

By calling the parent class method using super(), you can reuse the existing functionality implemented in the parent class. This promotes code reusability and reduces duplication. Instead of rewriting the entire logic of the parent class method in the child class, you can leverage the parent class implementation and build upon it.

Maintaining Code Coherence

Calling the parent class method using super() helps maintain code coherence and consistency. It ensures that the core behavior defined in the parent class method is preserved, even if the child class overrides it. This is particularly important when working with large codebases or teams, as it allows developers to understand and predict the behavior of inherited methods across the class hierarchy.

Extensibility and Customization

The super() function provides a way to extend or customize the behavior of the parent class method. By calling the parent class method first using super(), you can perform any necessary preprocessing or additional operations before or after invoking the parent class method. This allows you to build upon the existing functionality and tailor it to specific requirements in the child class.

Adapting to Future Changes

Using super() to call parent class methods enables adaptability to future changes in the codebase. If the implementation of the parent class method is updated or modified, the changes automatically propagate to the child class through the super() call. This ensures that the child class continues to benefit from improvements or bug fixes made to the parent class method without requiring explicit updates in the child class.

Practical Examples

Let's explore a couple of practical examples to better understand how to call parent class methods using super().

Example

class Vehicle:
   def start(self):
      print("Vehicle started.")

class Car(Vehicle):
   def start(self):
      super().start()  # Call the parent class method
      print("Car started.")

car = Car()
car.start()

Output

Vehicle started.
Car started.

In this example, the Car class overrides the start() method defined in the Vehicle class. By calling super().start(), the parent class method is invoked first, printing "Vehicle started." Then, the child class adds its own functionality by printing "Car started."

Example

class Shape:
   def __init__(self, color):
      self.color = color

   def draw(self):
      print(f"Drawing a shape with color: {self.color}")

class Circle(Shape):
   def __init__(self, color, radius):
      super().__init__(color)
      self.radius = radius

   def draw(self):
      super().draw()  # Call the parent class method
      print(f"Drawing a circle with radius: {self.radius}")

circle = Circle("Red", 5)
circle.draw()

Output

Drawing a shape with color: Red
Drawing a circle with radius: 5

In this example, the Circle class inherits from the Shape class and overrides the draw() method. By calling super().draw(), the parent class method is called first, printing "Drawing a shape with color: Red". Then, the child class adds its own functionality by printing "Drawing a circle with radius: 5".

These examples demonstrate how super() can be used to call parent class methods and extend their functionality in child classes.

Conclusion

Here, we explored how to call a parent class method in Python. We discussed method overriding and how you can use the super() function to call the parent class method from the child class. This technique allows you to extend or modify the functionality of the parent class method while retaining its original behavior.

Updated on: 14-Aug-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements