Declaring an Abstract Base Class
Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class. The rule is every abstract class must use ABCMeta metaclass.
ABCMeta metaclass provides a method called register method that can be invoked by its instance. By using this register method, any abstract base class can become an ancestor of any arbitrary concrete class. Let’s understand this process by considering an example of an abstract base class that registers itself as an ancestor of dict.
Python3
import abc class AbstractClass(metaclass = abc.ABCMeta): def abstractfunc( self ): return None print (AbstractClass.register( dict )) |
Output:
<class 'dict'>
Here, dict identifies itself as a subclass of AbstractClass. Let’s do a check.
Python3
import abc class AbstractClass(metaclass = abc.ABCMeta): def abstractfunc( self ): return None AbstractClass.register( dict ) print ( issubclass ( dict , AbstractClass)) |
Output:
True
Abstract Base Class (abc) in Python
Have you ever thought about checking whether the objects you are using adheres to a particular specification? It is necessary to verify whether an object implements a given method or property, especially while creating a library where other developers make use of it. A developer can use hasattr or isinstance methods to check whether the input conforms to a particular identity. But sometimes it is inconvenient to use those methods to check a myriad of different properties and methods.
As a solution to this inconvenience, Python introduced a concept called abstract base class (abc). In this section, we will discuss the abstract base class and its importance.
- Abstract Base Class
- Declaring an Abstract Base Class
- Why declare an Abstract Base Class?
- Abstract Properties
- Built-In Abstract Classes
Contact Us