How to Implement Interface in Python and Save Time

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

@abstractmethod
def name_method(self): #abstract method without body
pass


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):
@abstractmethod
def mybranch(self):
pass
myobj = Myengineer()


Output

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):
@abstractmethod
def mybranch(self):
pass

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

Related

Post a Comment

Thanks for your message. We will get back you.

Previous Post Next Post