Python Abstract Method and Class

An abstract method is a method whose action is redefined in the sub classes as per the requirement of the objects. Generally abstract methods are written without body since their body will be defined in the sub classes anyhow. But it is possible to write an abstract method with body also. To mark a method as abstract, we should use the decorator @abstractmethod. On the other hand, a concrete method is a method with body.

An abstract class is a class that generally contains some abstract methods. Since, abstract class contains abstract methods whose implementation (or body) is later defined in the sub classes, it is not possible to estimate the total memory required to create the object for the abstract class. So, PVM cannot create objects to an abstract class.

Once an abstract class is written, we should create sub classes and all the abstract methods should be implemented (body should be written) in the sub classes. Then, it is possible to create objects to the sub classes.

In next Program, we create Myclass as an abstract super class with an abstract method calculate(). This method does not have any body within it. The way to create an abstract class is to derive it from a meta class ABC that belongs to abc (abstract base class) module as:

class Abstractclass(ABC):

Since all abstract classes should be derived from the meta class ABC which belongs to abc (abstract base class) module, we should import this module into our program. A meta class is a class that defines the behavior of other classes.

The meta class ABC defines that the class which is derived from it becomes an abstract class. To import abc module's ABC class and abstractmethod decorator we can write as follows:

from abc import ABC, abstractmethod


from abc import *

Now, our abstract class 'Myclass' should be derived from the ABC class as:

classs Myclass(ABC):


def calculate(self, x):

pass #empty body, no code

This class has an abstract method calculate() that does not contain any code. We used @abstractmethod decorator to specify that this is an abstract method. We have to write sub classes where this abstract method is written with its body (or implementation).

A Python program to create abstract class and sub classes which implement the abstract method of the abstract class.

abstract car class example

Abstract Car Class and its Sub Classes

A Python program to create a Car abstract class that contains an instance variable, a concrete method and two abstract methods. #This is an abstract class. Save this code as

A Python program in which Maruti sub class implements the abstract methods of the super class, Car.

A Python program in which Santro sub class implements the abstract methods of the super class, Car.