Dremendo Tag Line

Abstract Classes in Python Programming

OOPs in Python

In this lesson, we will understand what is Abstract Class in Python Programming and how to create them along with some examples.

What is Abstract Class in Python?

An abstract class is a class that contains some abstract methods. Abstract methods are methods that are declared without their body. Later their bodies are declared in the sub-classes that inherit the abstract class.

Note: As abstract class contains abstract methods whose bodies must be declared or overridden in sub-classes, we can't create any object of the abstract class. An abstract class may also contain concrete methods with a defined body. Generally, concrete methods are normal methods with their body defined.

We create an abstract class by inheriting the metaclass ABC, which belongs to the module abc (abstract base class). A metaclass is a class that defines how a class will behave.

We create an abstract method using the decorator @abstractmethod, which belongs to the module abc.

To create an abstract class and abstract method in python, we first have to import the module abc into our program. See the example given.

video-poster

Importing ABC metaclass and abstractmethod decorator

from abc import ABC, abstractmethod

Or we can import like this.

from abc import *

Let's create and implement an abstract class with some abstract and concrete methods.

Example

from abc import *

class Data(ABC):
    @abstractmethod
    def calculate(self, x):
        pass

    @abstractmethod
    def area(self, x=0, y=0):
        pass

    def interest(self, p, r, t):
        return (p*r*t)/100


class Demo(Data):
    def calculate(self, x):
        return x*x*x

    def area(self, x=0, y=0):
        return x*y


x = Demo()
print('Cube of 5 = %d' %(x.calculate(5)))

print('Length  = 10');
print('Breadth = 5');
print('Area = %d' %(x.area(10,5)))

print('Principal = 5000')
print('Rate = 10%')
print('Time = 1 Year')
print('Simple Interest = %.2f' %(x.interest(5000,10,1)))

Output

Cube of 5 = 125
Length  = 10
Breadth = 5
Area = 50
Principal = 5000
Rate = 10%
Time = 1 Year
Simple Interest = 500.00

In the above example, we have created an abstract class Data that contains two abstract methods named calculate and area with a pass statement in their body. The pass statement is used when we don't want to define a body or execute any code. The class also contains a concrete method named interest that calculates and returns the simple interest.

We have also created another class, Demo, which inherits the abstract class Data. We defined the bodies of the abstract methods in Demo class. After that, we created an object x of the sub-class Demo and invoked all its methods.