Class in python interface

Interface in Python

This Python tutorial explains everything about What is an interface in Python with examples, And also interface vs abstract class in Python.

Interface in Python

  • An interface in Python 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 an 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 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.

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 the implementer decorator in class.
  • This package exports attributes and interfaces directly.
  • To overcome the uncertainty of the interface zope module is implemented.
Читайте также:  Php sql database code

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

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 is returned because I have defined two functions def food and def colddrinks in a class.

The below image shows the output:

interface in python

Create a Python interface

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

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, or tuple.
  3. __contain__ – This method is used to check whether it contains another string.
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)) is 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. The below screenshot shows the output:

interfaces in python

Formal interface in Python (ABCs)

Here, we can see a formal interface in Python.

  • A formal interface in Python 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 amodule 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.
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))

The 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.

what is interface in python

Python interface examples

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

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.

what is interface in python with example

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().

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:

difference between abstract class and interface in python

Difference between abstract class and interface in Python

Let us understand the difference between abstract class and interface in Python.

Python interface Python 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 abstract An 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 the below topics:

  • What is an Interface in Python?
  • How to Declare an Interface in Python
  • How to create an interface in Python
  • Python interface examples
  • Python multiple interfaces
  • difference between abstract class and interface in python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Оцените статью