...
/Abstract Base Class and Concrete Class
Abstract Base Class and Concrete Class
Learn about creating and implementing an abstract base class and implementing it in a concrete class using Python.
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:
class MediaLoader(abc.ABC):@abc.abstractmethoddef play(self) -> None:...@property@abc.abstractmethoddef ext(self) -> str:...
The abc.ABC
class introduces a metaclass—a class used to build the concrete class definitions. Python’s default metaclass is named type
...