Sitemap

Abstract Classes in Python

2 min readAug 18, 2021

--

Think of a computer, what comes to your mind?

A computer works on the instructions provided to it by the users, although a computer has its own resources but without any instructions it is just a piece of machine kept in the corner of your room.

Similarly, an abstract class is just any class in a program which is of no use until it is provided with some instructions or extended. The same can be said about abstract methods.

So, what is the use of such classes or methods?

Abstract classes and methods are used when there is some common behaviour or property between other classes with a slight variation and we want to minimize our code, in that case we can take advantage of abstract classes.

More formally we define abstract classes as a blueprint for other classes. It contains one or more abstract methods which can be utilized by its child classes.

Why are abstract classes used?

Get VEDANT MEHROTRA 1941049’s stories in your inbox

Join Medium for free to get updates from this writer.

As discussed earlier, abstract classes can be extended or inherited by child classes and various child classes get access to the same method but with different functionalities.

Implementation of Abstract Classes in Python-

By default, Python does not contain the definition of abstract classes, instead we have to import them. To do so we import ABC module and abstractmethod decorator from the abc package.

Press enter or click to view image in full size

In the above example, we start with importing ABC Module and abstractmethod decorator from the package ‘abc’.

Then we start off by defining our abstract base class ‘Ball’ which takes ABC as an argument and inside it we declare definition() method which is defined along with the ‘abstractmethod’ decorator which implies that it is an abstract method.

Finally we define the implementation classes of the abstract base class namely ‘cricketBall’ and ‘footBall’ which contains the implementation of the abstract method ‘definition()’ and includes a print statement describing the definition of each type of balls respectively. To conclude the program, the objects of both the implementations of the abstract classes are created and the abstract method is called.

Here, ball is an abstract class which indicates different types of balls are used in sports, namely for cricket and football.

Ball is the abstract class and definition() is the abstract method.

cricketBall and footBall are the child classes of the abstract class Ball.

Conclusion-

To conclude, abstract classes are a special type of class which contains only the definition of classes and/or methods and they can be implemented using other classes. We use abstract classes to when some common behaviour or functionality is present in different classes.

--

--