An abstract class is basically the blueprint of a class. An abstract class in python is the same as the initial definition. This class allows the user to create a set of methods that must be created within any subclasses built from the abstract class, considering it as the main class. A class that contains one or more abstract methods is called an abstract class. An abstract method is a method that has a declaration but does not have an implementation. While we are designing large functional units we use an abstract class. When we want to provide a common interface for different implementations of a component, we use an abstract class.
Abstract base class in Python
The user can have a common API by having an abstract base class for a set of child classes. This capability is especially useful in situations where a third-party is going to provide implementations, such as with plugins, but can also help you when working in a large team or with a large code-base where keeping all classes in your mind is difficult or not possible.
Python cannot provide abstract classes by default, they have to be created by the user. Python comes with a module that provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by decorating methods of the base class as abstract and then registering concrete classes as implementations of the abstract base. A method becomes abstract when decorated with the keyword @abstractmethod.
Python program to understand Abstract class
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Circle(Polygon):
# overriding abstract method
def noofsides(self):
print("I have no sides")
class Triangle(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 6 sides")
class Quadrilateral(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 4 sides")
# Driver code
A = Circle()
A.noofsides()
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()
Output
I have no sides
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides
Summary
- Abstract classes are classes that you cannot create instances from.
- Use
abc
module to define abstract classes. - An abstract is the blueprint of a class.