Interfaces in Python
Protocols and ABCs
Interview Relevant: API design
Interfaces
Python uses ABCs and Protocols for interfaces.
Code Examples
Interfaces with ABC and Protocol.
python
1from abc import ABC, abstractmethod
2from typing import Protocol
3
4# ABC approach
5class Drawable(ABC):
6 @abstractmethod
7 def draw(self):
8 pass
9
10# Protocol approach (Python 3.8+)
11class Drawable(Protocol):
12 def draw(self) -> None: ...
13
14# Any class with draw() matches Protocol
15class Circle:
16 def draw(self):
17 print("Drawing circle")
18
19def render(item: Drawable):
20 item.draw()
21
22render(Circle()) # Works! Circle has draw()