How to call a base class method using super() in Python?

PythonPythonBeginner
Practice Now

Introduction

Python's object-oriented programming (OOP) features provide a powerful way to create and manage complex applications. One of the key concepts in OOP is inheritance, which allows you to create new classes based on existing ones. In this tutorial, we'll explore how to use the super() function to call base class methods in Python, and discuss practical applications of this technique.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python/ObjectOrientedProgrammingGroup -.-> python/inheritance("`Inheritance`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/class_static_methods("`Class Methods and Static Methods`") subgraph Lab Skills python/inheritance -.-> lab-395040{{"`How to call a base class method using super() in Python?`"}} python/constructor -.-> lab-395040{{"`How to call a base class method using super() in Python?`"}} python/polymorphism -.-> lab-395040{{"`How to call a base class method using super() in Python?`"}} python/class_static_methods -.-> lab-395040{{"`How to call a base class method using super() in Python?`"}} end

Introduction to Inheritance in Python

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class to be based on an existing class. The new class, called the derived or child class, inherits the data and behaviors of the existing class, called the base or parent class. This allows for code reuse and the creation of hierarchical relationships between classes.

In Python, inheritance is achieved using the class keyword, where the derived class is defined by specifying the parent class in parentheses after the class name.

class ParentClass:
    def parent_method(self):
        print("This is a method of the parent class.")

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

In the example above, ChildClass inherits from ParentClass, which means that ChildClass has access to all the attributes and methods defined in ParentClass.

classDiagram ParentClass <|-- ChildClass ParentClass : +parent_method() ChildClass : +child_method()

Inheritance allows for the creation of specialized classes that build upon the functionality of their parent classes. This promotes code reuse, maintainability, and the creation of hierarchical relationships between classes.

Calling Base Class Methods with super()

When working with inheritance in Python, there may be times when you need to call a method from the base class within the derived class. This is where the super() function comes in handy.

The super() function allows you to call a method from the base class within the derived class. This is particularly useful when you want to extend the functionality of a base class method in the derived class.

class ParentClass:
    def parent_method(self):
        print("This is a method of the parent class.")

class ChildClass(ParentClass):
    def child_method(self):
        super().parent_method()
        print("This is a method of the child class.")

In the example above, the child_method() of the ChildClass calls the parent_method() of the ParentClass using the super() function, and then adds additional functionality.

Accessing Overridden Base Class Methods

When a derived class defines a method with the same name as a method in the base class, the derived class method overrides the base class method. In such cases, you can still access the overridden base class method using super().

class ParentClass:
    def parent_method(self):
        print("This is a method of the parent class.")

class ChildClass(ParentClass):
    def parent_method(self):
        super().parent_method()
        print("This is the overridden method of the child class.")

In the example above, the ChildClass overrides the parent_method() of the ParentClass, but it still calls the base class implementation using super().parent_method().

Calling Constructors with super()

The super() function can also be used to call the constructor (i.e., the __init__() method) of the base class from the derived class.

class ParentClass:
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2

class ChildClass(ParentClass):
    def __init__(self, param1, param2, param3):
        super().__init__(param1, param2)
        self.param3 = param3

In the example above, the ChildClass constructor calls the __init__() method of the ParentClass using super().__init__(), and then adds an additional parameter param3.

By using super(), you can ensure that the base class methods are properly called and the inheritance hierarchy is maintained, making your code more modular, maintainable, and extensible.

Practical Applications of super()

The super() function has several practical applications in Python programming, including:

Implementing Mixins

Mixins are a way to add functionality to a class by inheriting from multiple base classes. When using mixins, super() can be used to ensure that the methods of all the base classes are properly called.

class LoggingMixin:
    def log(self, message):
        print(f"Logging: {message}")

class CalculatorMixin:
    def add(self, a, b):
        return a + b

class CalculatorWithLogging(CalculatorMixin, LoggingMixin):
    def add(self, a, b):
        self.log(f"Adding {a} and {b}")
        return super().add(a, b)

In the example above, the CalculatorWithLogging class inherits from both CalculatorMixin and LoggingMixin. The add() method in CalculatorWithLogging calls the log() method from LoggingMixin and then uses super().add() to call the add() method from CalculatorMixin.

Implementing Abstract Base Classes (ABCs)

super() can be useful when working with Abstract Base Classes (ABCs) in Python. ABCs define a common interface for a group of related classes, and super() can be used to ensure that the abstract methods are properly implemented in the derived classes.

from abc import ABC, abstractmethod

class AbstractBaseClass(ABC):
    @abstractmethod
    def abstract_method(self):
        pass

class ConcreteClass(AbstractBaseClass):
    def abstract_method(self):
        super().abstract_method()
        print("Implementing the abstract method.")

In the example above, the ConcreteClass implements the abstract_method() defined in the AbstractBaseClass by calling super().abstract_method(), which ensures that the abstract method is properly implemented.

Handling Multiple Inheritance

When working with multiple inheritance, super() can help manage the method resolution order (MRO) and ensure that the methods of all the base classes are properly called.

class A:
    def method(self):
        print("Method from class A")

class B(A):
    def method(self):
        super().method()
        print("Method from class B")

class C(A):
    def method(self):
        super().method()
        print("Method from class C")

class D(B, C):
    def method(self):
        super().method()
        print("Method from class D")

In the example above, the D class inherits from both B and C, which both inherit from A. By using super().method(), the method() of each base class is properly called, following the correct MRO.

By understanding and utilizing the super() function, you can write more robust, maintainable, and extensible Python code that effectively leverages the power of inheritance and composition.

Summary

By the end of this tutorial, you'll have a solid understanding of how to use the super() function to call base class methods in Python. This knowledge will help you write more modular, maintainable, and extensible code, making you a more proficient Python programmer. Whether you're a beginner or an experienced developer, this guide will equip you with the skills to effectively leverage inheritance and super() in your Python projects.

Other Python Tutorials you may like