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.
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
a = Exhaust()
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.
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()
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
class NoBrand(Exhaust): pass d = NoBrand()
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 firstname.lastname@example.org