Abstract Base Class and Concrete Class
Learn to create abstract base classes with Python's abc module to define common interfaces for subclasses. Understand how to implement concrete classes that fulfill abstract methods, enabling robust design and type checking in OOP applications.
We'll cover the following...
Imagine we are creating a media player with third-party plugins. It is advisable to create an abstract base class (ABC) in this case to document what API the third-party plugins should provide (documentation is one of the stronger use cases for ABCs).
Creating an abstract base class
The general design is to have a common feature, like play(), that applies to several classes. We don’t want to pick some particular media format to use as a superclass; it seems somehow wrong to claim that some format is foundational and all others are derived from it.
We’d prefer to define the media player as an abstraction. Each unique media file format can provide a concrete implementation of the abstraction.
The abc module provides the tools to do this. Here’s an abstract class that requires a subclass to provide a concrete method and a concrete property to be useful:
The abc.ABC class introduces a metaclass—a class used to build the concrete class definitions. Python’s default metaclass is named type ...