How to Implement Interface in Python

In Python, we can create an interface class. It is used to specify a behavior that classes must implement. It is defined as the abstract type used to specify the behavior of a class. It is mainly used for achieving abstraction. For example, we can use an interface for performing multiple inheritance.

Implement Interface in Python

To implement the interface in Python, use the built-in ABC module. Interface functions are declared as abstract. An interface in Python is a collection of method signatures that should be provided by the implementing class.

Syntax

import abc


class Interface_class_name(abc.ABC):
  @abc.abstractmethod
  def function_name(self):
    pass


class Implement_class_name(Interface_class_name):
  def function_name(self):
    pass

Python program for Implementing interface in Python

import abc


class Shapes(abc.ABC):
  @abc.abstractmethod
  def area(self):
    print("You can find the area of every shapes using this interface")


class square(Shapes):
  def area(self, a):
    area = a**2
    print("Area of square is: " + str(area))


class rectangle(Shapes):
  def area(self, l, w):
    area = l * w
    print("Area of rectangle is: " + str(area))


class triangle(Shapes):
  def area(self, h, b):
    area = 0.5 * h * b
    print("Area of triangle is: " + str(area))


s = square()
s.area(4)
r = rectangle()
r.area(5, 3)
t = triangle()
t.area(6, 5)  

Output

Area of square is: 16
Area of rectangle is: 15
Area of triangle is: 15.0

In this program, we created an interface class using the module called abc. This abc class has a class called ABC, which is used for creating the interface class.

We have created an interface class named Shapes. This interface consists of an abstract method called the area. This area() function is made by using a decorator called abstractmethod.

This abstract method should be overridden in all the classes implemented from this interface class. We created three-class names square, rectangle, and triangle.

We implemented an interface class in the parameter in all these classes. We can see that we have used the interface class name in the parameter.

Using an interface name in the child class, we can implement the interface class. In all these classes, we have overridden the area function. We have found the area for each shape and have printed the area. 

We have created objects for all the child classes and have passed the values to the class. Finally, the function uses the arguments to calculate the area.

Hence, we implemented the interface using a module called abc.

That’s it for this tutorial.

Related posts

How to Join Multiple Paths in Python

Python int() vs floor(): The Difference

How to Read First Line of File in Python

Leave a Comment