How do I implement interfaces in python?

23    Asked by forira_6870 in Python , Asked on May 21, 2025

How do you implement interfaces in Python, given that it doesn’t have a built-in interface keyword like some other languages? What are the common ways to create and use interfaces in Pythonic style?

Answered by Morita Miyamoto

In Python, unlike languages like Java or C#, there’s no direct interface keyword. However, you can still implement interfaces using a few Pythonic approaches that ensure your classes follow a specific structure or contract.

1. Using Abstract Base Classes (ABCs)

The most common and formal way to implement interfaces in Python is by using the abc module.

from abc import ABC, abstractmethod
class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass
class Dog(Animal):
    def make_sound(self):
        print("Bark!")

  • ABC stands for Abstract Base Class.
  • @abstractmethod marks a method that must be implemented by any subclass.
  • If a class inherits from Animal but doesn't implement make_sound(), Python will raise an error when you try to instantiate it.

2. Duck Typing (Pythonic way)

  • Python often follows the principle: “If it walks like a duck and quacks like a duck, it’s a duck.”
  •  This means you don’t have to use abstract base classes. You can just ensure that the class implements the required methods.

class Cat:
    def make_sound(self):
        print("Meow!")
def animal_sound(animal):
    animal.make_sound()

As long as the object passed to animal_sound() has a make_sound() method, it works.

Summary:

  • Use abc module for a more structured, Java-like interface.
  • Use duck typing for a more flexible, Pythonic approach.
  • Both methods are valid—it just depends on how strict you want to be with your code structure.



Your Answer

Interviews

Parent Categories