Introduction to Interface in Python
An interface acts as a template for designing classes. Interfaces also define methods the same as classes, but abstract methods, whereas class contains nonabstract methods. Abstract methods are those methods without implementation or which are without the body. So the interface just defines the abstract method without implementation. The implementation of these abstract methods is defined by classes that implement an interface. In this topic, we are going to learn about Interface in Python.
Python interface design is different from other programming languages like C++, Java, C# and Go; one difference is that all these languages use the keyword “interface”, whereas Python does not use it. Another difference is Python does not require that a class which is implements an interface to provide the definition for all the abstract methods of an interface.
How to Create Interface in Python?
There are two ways in python to create and implement the interface, which are –
- Informal Interfaces
- Formal Interfaces
1. Informal Interfaces
python informal interface is also a class that defines methods that can be overridden but without force enforcement. An informal interface also called Protocols or Duck Typing. The duck typing is actually we execute a method on the object as we expected an object to have, instead of checking the type of an object. If its beaver is the same as we expected, then we will be fine and go farther, else if it does not, things might get wrong, and for safety, we use a try..except block or hasattr to handle the exceptions to check the object have the particular method or not.
An informal interface in python is termed as a protocol because it is informal and cannot be formally enforced. It is mostly defined by templates or demonstrates in the documentations. Consider some of the methods we usually used – __len__, __iter__, __contains__ and all, which are used to perform some operation or set of protocols.
Let see an example of python code to implements the – __len__, __iter__, __contains__ methods to apply on user define class instance or object, as in the below-given code –
class Fruits : def __init__( self, ele) : self.__ele = ele def __contains__( self, ele) : return ele in self.__ele def __len__( self ): return len( self.__ele) Fruits_list = Fruits([ "Apple", "Banana", "Orange" ]) print(len(Fruits_list)) print("Apple" in Fruits_list) print("Mango" in Fruits_list) print("Orange" not in Fruits_list)
As in the above example code, class Fruits implement the __len__, and __contains__ methods, so on the instance of the Fruits class, we can directly use the len function to get the size and can check the membership by using the in operator. As in the above code, the __iter__ method (iterable protocol) is not implemented, so we would not iterate over the instance of the Fruits. Therefore an informal interface cannot be enforced formally.
2. Formal Interfaces
A formal Interface is an interface which enforced formally. In some situations, the protocols or duck typing creates confusion, like consider the example we have two classes FourWheelVehicle and TwoWheelVehicle both have a method SpeedUp( ), so the object of both class can speedup, but both objects are not the same even if both classes implement the same interface. So to resolve this confusion, we can use the formal interface. To create a formal interface, we need to use ABCs (Abstract Base Classes).
An ABC is simple as an interface or base classes define as an abstract class in nature and the abstract class contains some methods as abstract. Next, if any classes or objects implement or drive from these base classes, then these bases classes forced to implements all those methods. Note that the interface cannot be instantiated, which means that we cannot create the object of the interface. So we use a base class to create an object, and we can say that the object implements an interface. And we will use the type function to confirm that the object implements a particular interface or not.
Let see an example of python code to understand the formal interface with the general example where we are trying to create an object of the abstract class, as in the below-given code –
import abc class Myinterface( abc.ABC ) : @abc.abstractclassmethod def disp(): pass class Myclass( Myinterface ) : pass o1 = Myclass( )
In the above code, the Myclass class inherits abstract class Myinterface but not provided the disp() abstract method’s implementation. The class Myclass also becomes an abstract class and hence cannot be instantiated.
Examples of Interface in Python
Here are the following examples mention below
An example of python code for a derived class defines an abstract method.
import abc class Myinterface( abc.ABC ): @abc.abstractclassmethod def disp( ): pass #print(" Hello from Myclass ") class Myclass(Myinterface): def disp( ): pass o1=Myclass()
Example of python code for the derived class which defines an abstract method with the proper definition –
import abc class Myinterface( abc.ABC ): @abc.abstractclassmethod def disp( ): pass #print(" Hello from Myclass ") class Myclass(Myinterface): def disp(s): print(" Hello from Myclass ") o1=Myclass() o1.disp()
Example of python code to understand object types –
import abc class FourWheelVehicle (abc.ABC): @abc.abstractmethod def SpeedUp( self ): pass class Car(FourWheelVehicle) : def SpeedUp(self): print(" Running! ") s = Car() print( isinstance(s, FourWheelVehicle))
Example of python code abstract class implemented by multiple derive classes –
import abc class FourWheelVehicle (abc.ABC): @abc.abstractmethod def SpeedUp( self ): pass class Car(FourWheelVehicle) : def SpeedUp(self): print(" Running! ") class TwoWheelVehicle (abc.ABC) : @abc.abstractmethod def SpeedUp(self): pass class Bike(TwoWheelVehicle) : def SpeedUp(self) : print(" Running!.. ") a = Bike () s = Car() print( isinstance(s, FourWheelVehicle)) print( isinstance(s, TwoWheelVehicle)) print( isinstance(a, FourWheelVehicle)) print( isinstance(a, TwoWheelVehicle))
The interface is an interesting concept, which acts as a blueprint for designing classes. The approach to creates and implementing the interface in python is different from other programming languages. To create a formal interface, we need to use the ABCs class, as we have seen in the above examples.
This is a guide to Interface in Python. Here we discuss the two ways in python to create and implement the interface along with the examples. You may also have a look at the following articles to learn more –