Sobes.tech
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:

  1. Abstract Base Classes (ABC) from the abc module. 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
  1. 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.

  2. Protocols from the typing module (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.