Click to share! ⬇️

Python Interface Design Pattern

By using a combination of multiple inheritance and abstract classes, you can use a design pattern in Python called an Interface. Interfaces are a common technique in object-oriented programming and programming languages like C# and Java implement this feature natively. Interfaces aren’t actually part of the Python language itself, but you can still use this type of design pattern with Python. In interface is a promise, or contract, that forces a given class to implement a given behavior. We’ll see how to do this in Python now.

from abc import ABC, abstractmethod


class Networkdevice(ABC):
    def __init__(self):
        super().__init__()

    @abstractmethod
    def poweron(self):
        pass


class Routify(ABC):
    @abstractmethod
    def route(self):
        pass


class Router(Networkdevice, Routify):
    def __init__(self):
        super().__init__()

    def poweron(self):
        print('Ready to process traffic')

    def route(self):
        print('Routify success')


r = Router()
r.poweron()
r.route()
Ready to process traffic
Routify success

The code above makes use of an Abstract Base Class which we learned about a short time ago. There is also multiple inheritance happening on line 19 where the Routify class is being passed in to the Router class as the second parameter. The interface is defined in the highlighted lines from 13 through 16. This class inherits from ABC, and it is used to define a contract. It doesn’t actually do anything, it’s almost like documentation. You can now use this class to enforce a rule on other classes to make sure they implement the route() method. In the code above, we inherit the Routify class in the Router class. Since this is the case, then this Router must implement the route() method. If it is not implemented, an error will be thrown and the code will not run.

Click to share! ⬇️