Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Interface in Python
    python

    Interface in Python

    March 30, 2023No Comments5 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Introduction to Interface in Python

    An interface may be used as a starting point for creating new classes. Interfaces are similar to classes in that they both specify methods, however unlike classes, interfaces only define abstract methods. Methods that have no body or implementation are considered abstract. Hence, the abstract method definition is all that is included in the interface. Classes that adhere to an interface specification determine how these abstract functions are actually implemented. The Python concept of Interface will be covered here.

    One way in which Python differs from other programming languages in terms of interface design is that although languages like C++, Java, C#, and Go all make use of the keyword “interface,” Python does not. Python is distinct in that it does not insist that a class which implements an interface also define all of the interface’s abstract functions.

    How to Create Interface in Python?

    The interface may be built and implemented in one of two ways in python:

    –

    • Informal Interfaces
    • Formal Interfaces

    1. Informal Interfaces

    Python’s informal interface is a class that defines overridable functions without requiring strict adherence to the original implementation. Protocols or Duck Typing refer to an informal interface. With duck typing, rather of verifying an object’s type, we just call a method on it to get the desired result. For safety, we utilise a try..except block or hasattr to handle exceptions and determine whether or not the object in question has the specified method. If its behaviour matches our expectations, we may proceed.

    Python’s name for an unofficial interface that can’t be officially enforced is “protocol.” Templates and examples may be found in the documentation to help define it. You may be familiar with some of the most common methods we’ve used, such as __len__, __iter__, __contains__, and all. Example

    Python code demonstrating the __len__, __iter__, and __contains__ methods applied to an instance of a user-defined class is provided below.

    Resulting 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)
    :

    Interface in Python

    The preceding code demonstrates that the Fruits class implements the __len__ and __contains__ methods, allowing us to directly utilise the len function to get the size and the in operator to verify membership. Due to the absence of the __iter__ method (iterable protocol) in the aforementioned code, it is not possible to perform an iteration over the Fruits instance. Hence, it’s impossible to mandate a casual relationship between the two

    formally.

    2. Formal Interfaces

    A formal interface is one that is strictly enforced. Consider the case where two classes, FourWheelVehicle and TwoWheelVehicle, both have a method called SpeedUp(), allowing objects of both classes to speed up, but these objects are not identical even if they both implement the same interface due to the use of protocols or duck typing. Hence, we can utilise the formal interface to clear this out once and for all. We need to employ the alphabet to design a proper user interface (Abstract Base Classes).

    The definition of an abstract base class (ABC) is as straightforward as that of an interface or base class, and the abstract class itself often has a few abstract methods. The next step is that these base classes must implement all the methods that are implemented or driven by any classes or objects that use them. Keep in mind that we can’t build an instance of the interface since its interface cannot be instantiated. As a result, we can claim that an object that derives from a certain base class implements the specified interface. Now we’ll check whether an object follows a certain interface with the help of the type function. Example

    To further grasp the abstract class’s formal interface, let’s have a look at some sample code written in Python, such as the one provided below: Code:

    Product Code: import abc
    class Myinterface( abc.ABC ) :
    @abc.abstractclassmethod
    def disp():
    pass
    class Myclass( Myinterface ) :
    pass
    o1 = Myclass( )

    Interface in Python

    In the code above, the Myclass class inherits from the abstract Myinterface class but does not offer an implementation for the disp() abstract function. Once Myclass is an abstract class, it can no longer be inherited.

    instantiated.

    Examples of Interface in Python

    Several instances are listed below:

    below

    Example #1

    Python snippet demonstrating the definition of an abstract method in a derived class. Code:

    import abc
    class Myinterface( abc.ABC ):
    @abc.abstractclassmethod
    def disp( ):
    pass
    #print(" Hello from Myclass ")
    class Myclass(Myinterface):
    def disp( ):
    pass
    o1=Myclass()

    Example #2

    Python code demonstrating a derived class that correctly specifies an abstract method, as an example:

    Input: 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()
    Result:

    Interface in Python

    Example #3

    Python code sample explaining object classes:

    Final Product: 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))

    Interface in Python

    Example #4

    Here’s an abstract class written in Python that has numerous derived classes that really do the work.

    Resulting 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))

    Interface in Python

    Interface in Python Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleLinkedIn Social Authentication in Django
    Next Article Conditional Statements in Python ifelifelse

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.