How do I implement interfaces in python?

In Python, interfaces are not explicitly supported as they are in Java or C#. However, you can achieve interface-like behavior using abstract base classes (ABCs) provided by the abc module. Abstract base classes allow you to define methods that must be implemented by derived (subclass) classes, thus enforcing a contract.

Here’s how to implement interfaces in Python:

1. Using Abstract Base Classes (ABCs)

Step-by-Step Example

  1. Import the abc module.
  2. Create an abstract base class by subclassing abc.ABC.
  3. Use the @abstractmethod decorator to define methods that subclasses must implement.

Example:

from abc import ABC, abstractmethod # Define the interface using an abstract base class class Animal(ABC): @abstractmethod def speak(self): pass @abstractmethod def move(self): pass # Implement the interface in a subclass class Dog(Animal): def speak(self): return "Bark!" def move(self): return "Runs on four legs" class Bird(Animal): def speak(self): return "Chirp!" def move(self): return "Flies in the sky" # Using the subclasses dog = Dog() print(dog.speak()) # Output: Bark! print(dog.move()) # Output: Runs on four legs bird = Bird() print(bird.speak()) # Output: Chirp! print(bird.move()) # Output: Flies in the sky

Key Points:

  • The @abstractmethod decorator marks methods that must be implemented in any subclass.
  • Attempting to instantiate an abstract class or a subclass that doesn’t implement all abstract methods will raise a TypeError.

2. Using Duck Typing

Python relies heavily on duck typing, meaning you don’t need formal interfaces to enforce a contract. Instead, if an object implements the expected methods, it’s considered valid.

Example:

class Dog: def speak(self): return "Bark!" def move(self): return "Runs on four legs" class Bird: def speak(self): return "Chirp!" def move(self): return "Flies in the sky" # Function expecting an interface-like behavior def animal_actions(animal): print(animal.speak()) print(animal.move()) dog = Dog() bird = Bird() animal_actions(dog) # Output: Bark! Runs on four legs animal_actions(bird) # Output: Chirp! Flies in the sky

Key Points:

  • No explicit interface is needed. Any object implementing the required methods can be passed.
  • This approach is flexible but lacks compile-time guarantees.

3. Combining ABCs and Duck Typing

You can use abstract base classes as a guideline and still leverage Python’s duck typing to check if an object adheres to an interface.

Example:

from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def speak(self): pass @abstractmethod def move(self): pass def animal_actions(animal): if isinstance(animal, Animal): # Check if the object adheres to the interface print(animal.speak()) print(animal.move()) else: raise TypeError("Object does not implement the Animal interface") class Dog(Animal): def speak(self): return "Bark!" def move(self): return "Runs on four legs" dog = Dog() animal_actions(dog) # Output: Bark! Runs on four legs

4. Using collections.abc for Built-in Interfaces

Python provides predefined abstract base classes in the collections.abc module for common interfaces like iterable, mapping, etc.

Example:

from collections.abc import Iterable # Check if an object implements the Iterable interface print(isinstance([1, 2, 3], Iterable)) # Output: True print(isinstance(123, Iterable)) # Output: False

Summary

  1. Use abc.ABC and the @abstractmethod decorator to define and enforce interface-like behavior in Python.
  2. Leverage duck typing for flexible, informal interface behavior.
  3. Combine ABCs and type checking when you need both enforcement and runtime flexibility.
  4. Utilize built-in abstract base classes in collections.abc for standard interfaces.

For mastering Python programming and object-oriented design, explore Grokking Python Fundamentals and Grokking Advanced Coding Patterns for Interviews on DesignGurus.io. These courses are excellent for building a strong foundation and tackling real-world challenges!

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Is coding a good career?
How to prepare for coding interviews in Erlang?
What is the data type in C++?
What are the salary levels at Google?
Strategies to remain calm and focused under intense scrutiny
Which Docusign interview questions and answers to prepare?
Related Courses
Course image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
Discounted price for Your Region

$197

Course image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
Discounted price for Your Region

$78

Course image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
Discounted price for Your Region

$78

Image
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.