How to Create Abstract Base Class in Python

09/13/2021

Contents

In this article, you will learn how to create Abstract Base Class in Python.

How to Create Abstract Base Class

In Python, an Abstract Base Class (ABC) is a class that cannot be instantiated and is designed to be subclassed by other classes. The purpose of an ABC is to define a common interface that its subclasses must implement, and to provide some default implementation for some or all of the required methods.

To create an abstract base class in Python, you can use the built-in abc module. Here’s an example of how to define an ABC:

import abc

class MyABC(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def my_abstract_method(self):
        pass

    def my_concrete_method(self):
        print("This is a concrete method.")

In this example, MyABC is the name of our abstract base class. We use the metaclass parameter to tell Python that this class should be an abstract base class, and we set it to abc.ABCMeta. The abc module provides the abstractmethod decorator that we use to mark the my_abstract_method method as abstract. This method has no implementation and is designed to be overridden by subclasses.

We also define a concrete method, my_concrete_method, which has an implementation and can be inherited as-is by subclasses. However, subclasses are still required to implement my_abstract_method.

Here’s an example of how to create a subclass of MyABC:

class MySubclass(MyABC):
    def my_abstract_method(self):
        print("This is my implementation of the abstract method.")

In this example, we define a new class MySubclass that inherits from MyABC. We override the my_abstract_method method with our own implementation, and since we’ve provided an implementation for this method, MySubclass is no longer considered abstract.

If we create an instance of MySubclass, we can call both the abstract and concrete methods:

>>> obj = MySubclass()
>>> obj.my_abstract_method()
This is my implementation of the abstract method.

>>> obj.my_concrete_method()
This is a concrete method.

By creating an abstract base class with abstract methods, we can ensure that subclasses provide their own implementation of these methods, while also providing some default behavior through concrete methods. This can help make our code more modular and easier to maintain.