Implement Interface in Python

Ridwan Yusuf
2 min readJan 9, 2023

--

If you have had the opportunity to program in some object-oriented programming languages such as Java or C++, you may have encountered the term ‘interface’.

An interface defines a set of methods (behaviors) that a class must implement. An interface does not specify how these methods should be implemented, but rather delegates the implementation to the class.

There are several reasons why one might choose to use an interface: it provides assurance that the class will implement the specified methods, and it gives the class the freedom to implement them in whatever way it
wishes.

Though the concept of interface does not come built-in python, but it can implemented using Abstract base class and inheritance.

[*] Say we expect that every animal must exhibits the ‘eat’ and ‘move’
behavior(and Of course we are less concerned by how they do it by individual)

[*]Abstract class/Interface ->specifying the behaviors(eat&move) that every animal must exhibits

from abc import ABC, abstractmethod

class AbstractAnimalInterface(ABC):
@abstractmethod
def eat(self):
pass

@abstractmethod
def move(self):
pass

[*] Concrete class that must implement the behaviors

class Cat(AbstractAnimalInterface):
def eat(self):
print('Cat eats soooooooo fast')

def move(self):
print('Cat moves at an average speed')


class Duck(AbstractAnimalInterface):
def eat(self):
print('Duck eat so slowly')

[*]We intentionally omitted move() here in the Duck class.
There would be an error that we must implement move() before Duck class can function properly since it must implement all behaviors/method defined in the interface.

[*]Usage 1
cat = Cat()
cat.move()
cat.eat()

[*]Output
Cat moves on average speed
Cat eats soooooooo fast

[*]Usage 2
duck = Duck()

[*]Output
We are unable to instantiate the duck instance, let alone call any methods on it further. ☹️

Note: If all the different animals (such as cats and ducks in our own case) exhibited behaviors in exactly the same way, there would be no point in using an interface, as we would be duplicating the same thing in each method.

This is exactly where Mixin does a great job.

Check out Mixin:

Thanks for reading and feel free to explore my video collection on YouTube for more educational content. Don’t forget to subscribe to the channel to stay updated with future releases.

--

--

Ridwan Yusuf

RidwanRay.com -I provide engineers with actionable tips and guides for immediate use