In python, if you create a class with one or more abstract methods, we will call it an abstract class. An abstract method is a method that will contain only declaration, no implementation. The class that inherits from abstract base class needs to implement all the base class abstract methods.
Generally, the abstract classes are same as normal classes, but the only difference is the abstract classes will have one or more abstract methods. The abstract classes are useful when you want to provide a common interface for different implementations in derived classes.
Python won’t provide direct support to the abstract classes. To implement abstract classes in python, you need to import the ABC
(Abstract Base Classes) module and create the abstract methods in a base class. To create abstract methods, you need to create methods by decorating with the @abstractmethod
attribute.
Following is the example of creating the abstract classes in python.
If you observe the above example, we imported the python ABC module and created the abstract base class (User) with the abstract method (getDetails). The derived classes have provided the implementation for the base class abstract method.
The above python abstract class example will return the result as shown below.
As discussed, the abstract classes will have both abstract and non-abstract methods but, it won’t allow us to create an instance because they have incomplete abstract methods. Only the classes that are derived from the abstract base class will have the implementation of the abstract method. So, python will not allow us to create an instance for abstract classes.
Following is the example of creating an instance for an abstract class in python.
The above python abstract class example will return the result as shown below.
If you observe the above result, we got an exception because we tried to create an instance for the abstract class.
This is how you can create and use the abstract classes in python based on your requirements.