Introduction to Python Interface

In thisĀ Python tutorial, we will discuss the python interface and also we will check what is an interface in python with examples. Let us learn:

  • What is an interface in Python?
  • How to create an interface in Python?
  • What is the formal and informal interface in Python?
  • Python interface examples
  • Python interface vs abstract class

What is an Interface?

  • An interface is a collection of method signatures that should be provided by the implementing class.
  • An interface contains methods that are abstract in nature. The abstract methods will have the only declaration as there is no implementation.
  • An interface in python is defined using python class and is a subclass of interface.Interface which is the parent interface for all interfaces.
  • The implementations will be done by the classes which will inherit the interface. Interfaces in Python are a little different from other languages like Java or C# or C++.
  • Implementing an interface is a way of writing an organized code.

Let us understand the Python interfaces with a few examples.

How to declare an interface in Python

Here, we will see how to declare the interface module in Python.

Syntax:

class MyInterface(zope.interface.Interface)
  • Firstly, we will import zope.interface module.
  • The zope.interface is a module that is used to implement the object interface in python.
  • The zope.interface library is the way to come out of when something is not clear.
  • The interface act as a blueprint for designing classes. Here, @zope.interface.implementer(Lunch) is implemented using implementer decorator in class.
  • This package export attributes and interfaces directly.
  • To overcome the uncertainty of the interface zope module is implemented.

Implementation by(class) – This function returns a boolean value. If the class implements the interface it results in True else False.

Example:

import zope.interface 
class Lunch(zope.interface.Interface):
northindian = zope.interface.Attribute("chocolate")
def food(self, northindian):
pass
def colddrinks(self, beverages):
pass
@zope.interface.implementer(Lunch)

class Lunch(zope.interface.Interface):
def food(self, northindian):
return northindian
def colddrinks(self,beverages):
return beverages

colddrinks = Lunch['colddrinks']
food = Lunch['food']
print(Lunch.implementedBy(Lunch))
print(type(colddrinks))
print(type(food))

Here, we can see that the class is implemented in the interface. So, the boolean value true is returned. Also, we can see the output two times the <class ‘zope.interface.interface.Method’> is returned because I have defined two functions def food and def colddrinks in a class.

Below image shows the output:

Python interface module
Python interface module

Create a Python interface

There are two ways for creating and implementing the interface in python are –

  • Informal Interface
  • Formal Interface

Informal interface in python

An informal interface in Python is a class. It defines methods that can be overridden but without force enforcement. An informal interface in python is termed as a protocol because it is informal and cannot be enforced formally. The commonly used methods which are used to perform some operations are:

  1. __iter__ – This method returns an iterator for an object.
  2. __len__ – This method returns the length of string, list, dictionary, tuple.
  3. __contain__ – This method used to check whether it contains another string.

Example:

class Chocolate:
    def __init__(self, items):
        self.__items = items
    def __len__(self):
        return len(self.__items)
    def __contains__(self, items):
        return items in self.__items
fav_chocolate = Chocolate(["kitkat", "diarymilk", "munch","5star"])
print(len(fav_chocolate))
print("kitkat" in fav_chocolate)
print("munch" not in fav_chocolate)
print("dirymilk" not in fav_chocolate)
print("5star" in fav_chocolate)
  • In this example, I have implemented __len__ and __contain__. We can directly use the len() function on the chocolate instance, then we have to check for an item whether it is present in the list.
  • Using in operator, print(len(fav_chocolate)) used to find the length of the list.
  • Here, we can see that it returns a boolean value. If the item is present in the list it will return true else it will return false. Below screenshot shows the output:
Informal interface in python
Informal interface in Python

Formal interface in python(ABCs)

Here, we can see formal interface in python.

  • A formal interface is an interface which enforced formally. For creating a formal interface we need to use ABCs(Abstract Base Classes).
  • The ABCs is explained as we define a class that is abstract in nature, we also define the methods on the base class as abstract methods.
  • Any object we are deriving from the base classes is forced to implement those methods.
  • In this example, I have imported a module abc and defined a class Food. The @abc.abstractmethod is a decorator indicating abstract methods this is used to declare abstract methods for properties.
  • I have defined a function def taste using the def keyword, by using the self keyword we can access the attributes and methods of the class.
  • And, I have also defined a subclass as class north_indian and then printing an instance from the class food. The pass statement is used as a placeholder.

Example:

import abc
class Food (abc.ABC):
  @abc.abstractmethod
  def taste( self ):
      pass
class north_indian(Food) :
  def taste(self):
     print(" Cooking! ")
s = north_indian ()
print( isinstance(s, Food))

Below screenshot shows the output:

In this output, we can see that output a boolean value. It returns true only if the instance is present in the class else it returns false.

Formal interface in python(ABCs)
Formal interface in python(ABCs)

Python interface examples

Here, we will see how code for derived class defines an abstract method. So, we have imported abc module and we have the class name as myinterface(abc.ABC).

Example:

import abc
class myinterface(abc.ABC):
      @abc.abstractclassmethod
      def display():
        pass
print("This is Myclass")
class Myclass(myinterface):
      def display():
        pass
obj=Myclass()

Here, obj = Myclass() is called and it prints the output as “This is Myclass”. You can refer to the below screenshot for python interface examples.

Python interface examples
Python interface examples

Python multiple interfaces

Now, we can see multiple interfaces in Python.

In the below example, we have to import abc module, and then we can initialize the class as Food and subclass as northIndian() and southIndian().

Example:

import abc
class Food (abc.ABC):
  @abc.abstractmethod
  def taste( self ):
   pass
class northIndian(Food) :
  def taste(self):
   print(" Cooking! ")
class Food (abc.ABC):
   @abc.abstractmethod
   def taste(self):
    pass
class southIndian(Food) :
   def taste(self) :
    print(" Cooking!.. ")
a = northIndian ()
s = southIndian()
print( isinstance(s, northIndian))
print( isinstance(s, southIndian))
print( isinstance(a, northIndian))
print( isinstance(a, southIndian))

Here, we can see in the output as false because instance s is assigned to southIndian but in a print statement, it is assigned as (s, northIndian). We can refer to the below screenshots:

Python multiple interfaces
Python multiple interfaces

Python interface vs abstract class

Let us understand the difference between Python interface vs abstract class.

Python interfacePython abstract class
An interface is a set of methods and attributes on that object.We can use an abstract base class to define and enforce an interface.
All methods of an interface are abstractAn abstract class can have abstract methods as well as concrete methods.
We use an interface if all the features need to be implemented differently for different objects.Abstract classes are used when there is some common feature shared by all the objects as they are.
The interface is slow as compared to the abstract class.Abstract classes are faster.

You may like the following Python tutorials:

In this Python tutorial, we have learned about the Python interface. Also, We covered these below topics:

  • What is an Interface?
  • How to Declare an interface in Python
  • How to create an interface in Python
  • Python interface examples
  • Python multiple interfaces
  • Python interface vs abstract class