In this article, I would like to answer a common question that pops up in mind whenever we start to learn Object Oriented Programming in Python. But before we begin exploring the use case, first lets briefly discuss about what really is an abstract class in python:
Abstract Class is a class that contains one or more abstract methods. These abstract methods are methods without any implementation!
Sounds weird right? Actually it is true for most of the Object Oriented Programming Language. Abstract method has no implementation in other words no function body! Sub classes implement these abstract methods to fulfill their needs.
But, Python’s abstract method is somewhat different as it is possible to create abstract method with body in python! To know more about python’s abstract class checkout this tutorial
Now, lets move on to our original question when to use abstract class?
Use of Abstract Class
Abstract class is useful when we want to define many different classes with similar class structure e.g. with same method signatures. Now I will try to explain it with an example. Lets say we want to create classes for different shapes such as Triangle, Rectangle, Pentagon, Hexagon and so on…
In this case, you will find a lot of attributes that are common in each shape but, require different implementation.
For example, consider the attribute area, for all these shapes you will need different formulas to calculate area. Hence, for each classes of Triangle, Rectangle and other shapes there will always be a method called area which will calculate area but, the implementation of this method ‘area’ will vary from one to another.
Like the area attribute there are tons of different attributes that are common in each shape but requires different implementation for each classes. These common properties will be pretty cumbersome to handle if we don’t group them.
Thus, it opens up an opportunity to abstract things little bit so that we can maintain them in a better way.
We can simply create an Abstract class and name it say as `Polygon` with all the common attribute/properties of shapes and, use it to create rest of the classes for different shapes.
from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass
The plus point is, abstract class can’t be instantiated. So, object creation by instantiating the Abstract Class
Polygon won’t be possible.
If you try to instantiate the Polygon object like below:
obj = Polygon()
It will raise an Exception
TypeError: Can't instantiate abstract class Polygon with abstract methods area
Now that we have our abstract base class for different shapes we can create different sub classes for these shapes just like below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|from abc import ABC, abstractmethod|
|def __init__(self, a, b, c, base, height):|
|self.a, self.b, self.c = a, b, c|
|self.base, self.height = base, height|
|return 1/2 * self.base * self.height|
|return self.a + self.b + self.c|
|def __init__(self, a):|
|self.a, = a|
|return self.a * self.a|
|return 2 * self.a|
|obj = Triangle(a=1, b=2, c=3, base=2, height=3)|
|# The following line will raise|
|# TypeError: Can't instantiate abstract class Polygon with abstract methods area|
|# obj = Polygon()|
P.S. Whenever you find a situation where many of your classes has a common structure but require different implementations you can use abstract class to construct a Base Class for abstraction.
Why Abstract Class is necessary?
Abstract class offer many things such as semantic contract between clients & class implementations, also provides protection from missing implementations of must needed methods of sub classes. It means rather than getting an AttributeError at run time just to know that you forgot to implement something really important, the abstract class will let you know straight at initialization that you have forgotten to implement an important method(abstract)!
By making sure at instantiation time that the sub classes implement some particular methods while maintaining class hierarchy Python’s Abstract Base class saves you from bugs and overheads.
I would recommend reading this stack overflow question and answers for the in depth discussion on the above question.