Writing Interface in Python

Posted by Afsal on 18-Nov-2022

Hi Pythonistas

Today we will learn how to write Interface in Python. In Python, this is achieved by using a module called abc. Let us learn with an example. 

Consider We have an Interface called Exhaust. 

Code

import abc

class Exhaust(abc.ABC):
    @abc.abstractmethod
    def sound(self):
        pass 

Interface are looks as normal class but we cannot make a object using this class. If we try to create then it will throw an Exception

Code

a = Exhaust()

Output

Traceback (most recent call last):
  File "interface.py", line 28, in <module>
    a = Exhaust()
        ^^^^^^^^^
TypeError: Can't instantiate abstract class Exhaust with abstract method sound

Now we can create new classes using this interface.

Code

class Akrapovic(Exhaust):
    def sound(self):
        print("Wroom Wroom")

class Yoshimura(Exhaust):
    def sound(self):
        print("Broom Broom")

b = Akrapovic()
b.sound()

c = Yoshimura()
c.sound()

Output

Wroom Wroom
Broom Broom

Now in case if create class using this interface and doenot override the method sound, Then we cannot create the object of this class

Code

class NoBrand(Exhaust):
    pass 

d = NoBrand()

Output

Traceback (most recent call last):
  File "interface.py", line 34, in <module>
    d = NoBrand()
        ^^^^^^^^^
TypeError: Can't instantiate abstract class NoBrand with abstract method sound

Hope you have learned something from this post. Please share valuable suggestion with afsal@parseltongue.co.in