Aller au contenu

Protocols vs. ABCs

Abstract Base Classes (ABCs)

An interface defines a set of methods that a class must implement to be considered compatible with that interface.

from abc import ABC, abstractmethod

class MyABC(ABC):
    @abstractmethod
    def my_method(self):
        pass

class MyClass(MyABC):
    def my_method(self):
        # Implement the method functionality here
        pass

Python Protocols

Protocols allow you to specify the expected methods and attributes that a class should have without requiring explicit inheritance or modifications to the class hierarchy.

from typing import Protocol

class MyProtocol(Protocol):
    def my_method(self):
        pass

class MyClass:
    def my_method(self):
        # Implement the method functionality here
        pass

Example

from typing import Protocol

class Printable(Protocol):
    def __str__(self) -> str:
        pass

def print_object(obj: Printable) -> None:
    print(str(obj))

class MyClass:
    def __str__(self) -> str:
        return "This is an instance of MyClass"

print_object(MyClass())        # Output: This is an instance of MyClass

Ressources