Python Interfaces: Using Abstract Base Classes (ABC)
Discover how to use interfaces in Python through abstract base classes (ABC) and the @abstractmethod
decorator. Understand the key differences between abstract classes and interfaces, and learn the rules for implementing Python interfaces, including method abstraction and class implementation requirements.
Python - Interfaces
Introduction
An interface is a software architectural pattern similar to a class but with methods that only have prototype signature definitions without any executable code. The required functionality must be implemented by the methods of any class that inherits the interface. These methods are known as abstract methods.
Interfaces in Python
In languages like Java and Go, interfaces are defined using the interface
keyword. Python uses abstract base classes (ABC) and the @abstractmethod
decorator to create interfaces.
Note: Abstract classes in Python are also created using the ABC module. The difference between an abstract class and an interface is that an abstract class can have non-abstract methods, while all methods in an interface must be abstract.
Rules for Implementing Python Interfaces
- Methods defined inside an interface must be abstract.
- Creating an object of an interface is not allowed.
- A class implementing an interface needs to define all the methods of that interface.
- If a class does not implement all the methods defined inside the interface, it must be declared abstract.
Ways to Implement Interfaces in Python
There are two ways to create and implement interfaces in Python:
- Formal Interface
- Informal Interface
Formal Interface
Formal interfaces in Python are implemented using the abstract base class (ABC) from the abc
module.
Example
from abc import ABC, abstractmethod
# Creating interface
class DemoInterface(ABC):
@abstractmethod
def method1(self):
pass
@abstractmethod
def method2(self):
pass
# Class implementing the above interface
class ConcreteClass(DemoInterface):
def method1(self):
print("This is method1")
def method2(self):
print("This is method2")
# Creating instance
obj = ConcreteClass()
# Method call
obj.method1()
obj.method2()
Output
This is method1
This is method2
Informal Interface
In Python, an informal interface refers to a class with methods that can be overridden, but the compiler cannot strictly enforce the implementation of all the provided methods. This type of interface works on the principle of duck typing.
Example
class DemoInterface:
def displayMsg(self):
pass
class NewClass(DemoInterface):
def displayMsg(self):
print("This is my message")
# Creating instance
obj = NewClass()
# Method call
obj.displayMsg()
Output
This is my message