ABC in Python (Abstract Base Class)

Photo by Michael Dziedzic on Unsplash

Introduction

An Abstract class is one of important concept in object oriented programming(oops). It is like blueprint for other classes.

Where we use abstract?

For larger projects, it is impossible to remember the class details, and also the reusability of code can increase the bug. Therefore, it plays a crucial role in our projects.

By default, Python does not provide abstract classes. The ‘abc’ module in the Python library provides the infrastructure for defining custom abstract base classes.

Abstract class cannot be instantiated in python. An Abstract method can be call by its subclasses.

The above module provides us the following,

  1. ABCMeta
  2. ABC ( helper class )

these are keywords used to create an abstract class.

ABCMeta:
It is a metaclass for defining the abstract class.

ABC:
It is a helper class. we can use it in the area where we want to avoid the confusion of metaclass usage.

Both the steps are similar.

Note: The type of ABC ( type(ABC) ) is still ABCMeta. therefore inheriting from ABC requires the usual precautions regarding metaclass usage, as multiple inheritance may lead to metaclass conflicts.

register():
We can make a concrete subclass or built-in subclass as a virtual subclass using the register. But it is not visible in the Method Resolution Order(MRO). Its method is not even callable using super().

@abstractmethod:

It is used to make the method of the abstract class as an abstract method.

The abstract methods can be called using any of the normal ‘super’ call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.

Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are not supported. The abstractmethod() only affects subclasses derived using regular inheritance; “virtual subclasses” registered with the ABC’s register() method are not affected.

There are other decorators (@abstractclassmethod, @abstractstaticmethod ) and also some magic methods available. We can discuss about that further.

These are the basics and most needed part of the ABC.

Thank You 🧡…..