Abstract Base Class (ABC) is a special class in Python that defines a set of interfaces and specifications rather than specific implementation details. It can be used as a base class for other classes. By inheriting the abstract base class, subclasses can implement the interfaces and specifications defined in the abstract base class. This article will introduce the usage of Python abstract base classes in detail and provide corresponding source code examples.
In Python, the definition of abstract base classes requires the use of abc
modules. Let’s import the module first abc
:
from abc import ABC, abstractmethod
The key to defining an abstract base class is to inherit ABC
the class and use @abstractmethod
decorators on methods that require abstraction. Here is a simple example that defines an abstract base class Shape
that contains an abstract method area
:
from abc import ABC, abstractmethod
class Shape(ABC