How to Create Interface in Python Though it Doesn't Support

Do you think Python support interface? Yes, but it is not directly. We will see the way how it supports. Below, you will find an example on python interface. The interface concept is explicitly not available in python. However, a feature is available in other programming languages like Java, C# and .Net. 

Python interface is an abstract class containing only an abstract method but not a single concrete method.

Python interface

Python abstract method

from abc import ABC, abstract method
class name_class(ABC): # abstract class

def name_method(self): #abstract method without body

The interface is used when all the features are needed to be implemented differently for different objects.

Python interface rules

  1. All methods of an interface are abstract.
  2. You cannot create an interface object.
  3. If any class implements an interface, then you need to define all the methods given in that interface.
  4. You need to declare all methods as abstract if that class does not implement the interface

Creating object with abstract class

from abc import ABC, abstractmethod
class Myengineer(ABC):
def mybranch(self):
myobj = Myengineer()


TypeError: Can’t instantiate abstract class Myengineer
with abstract methods mybranch

Program to impalement Python interface

You cannot create an object from an abstract class. But you can do it by creating a child class.

from abc import ABC, abstractmethod

#Abstract class
class Myengineer(ABC):
def mybranch(self):

#Child class implements abstract class
class MyEEE(Myengineer):
def mybranch(self):
print(“I am an electrical and electronics Engineer”)
myobj = MyEEE()


Post a Comment

Thanks for your message. We will get back you.

Previous Post Next Post