Junior — Middle
How can an interface be implemented in a programming language?
sobes.tech AI
Answer from AI
Python does not have a built-in keyword for interfaces like Java or C#. However, interfaces can be implemented in several ways:
- Abstract Base Classes (ABC) from the
abcmodule. They allow you to define methods that must be implemented in subclasses.
from abc import ABC, abstractmethod
class MyInterface(ABC):
@abstractmethod
def method(self):
pass
class Implementation(MyInterface):
def method(self):
print("Method implementation")
obj = Implementation()
obj.method() # Outputs: Method implementation
-
Duck Typing — in Python, types are often not checked explicitly; instead, methods are called assuming the object supports them. The main thing is that the object has the required methods.
-
Protocols from the
typingmodule (starting with Python 3.8) — allow describing interfaces for static type checking.
Thus, to implement an interface in Python, you usually use abstract base classes or rely on duck typing.