oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

    Python - Interfaces


    In software engineering, an interface is a software architectural pattern. An interface is like a class but its methods just have prototype signature definition without any body to implement. The recommended functionality needs to be implemented by a concrete class.

    In languages like Java, there is interface keyword which makes it easy to define an interface. Python doesn't have it or any similar keyword. Hence the same ABC class and @abstractmethod decorator is used as done in an abstract class.

    An abstract class and interface appear similar in Python. The only difference in two is that the abstract class may have some non-abstract methods, while all methods in interface must be abstract, and the implementing class must override all the abstract methods.

    Example

    from abc import ABC, abstractmethod
    class demoInterface(ABC):
       @abstractmethod
       def method1(self):
          print ("Abstract method1")
          return
    
       @abstractmethod
       def method2(self):
          print ("Abstract method1")
          return
    

    The above interface has two abstract methods. As in abstract class, we cannot instantiate an interface.

       obj = demoInterface()
             ^^^^^^^^^^^^^^^
    TypeError: Can't instantiate abstract class demoInterface with abstract methods method1, method2
    

    Let us provide a class that implements both the abstract methods. If doesn't contain implementations of all abstract methods, Python shows following error −

       obj = concreteclass()
             ^^^^^^^^^^^^^^^
    TypeError: Can't instantiate abstract class concreteclass with abstract method method2
    

    The following class implements both methods −

    class concreteclass(demoInterface):
       def method1(self):
          print ("This is method1")
          return
       
       def method2(self):
          print ("This is method2")
          return
          
    obj = concreteclass()
    obj.method1()
    obj.method2()
    

    Output

    When you execute this code, it will produce the following output −

    This is method1
    This is method2