When to use Abstract Class in Python?

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_base_class_python

Abstract Class

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:


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.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.