Python theorytheory 0/50 · 0%
OOP · hard

42. Working with abstract base classes and protocols

Defining interfaces with abc and structural typing.

`abc.ABC` and `@abstractmethod` define interfaces that subclasses must implement, raising `TypeError` if instantiated without fulfilling the contract.

python
from abc import ABC, abstractmethod

class ChainClient(ABC):
    @abstractmethod
    def get_balance(self, address: str) -> float:
        ...

class MockClient(ChainClient):
    def get_balance(self, address: str) -> float:
        return 1.5

`typing.Protocol` offers structural typing ("duck typing" checked statically): a class satisfies a Protocol just by having the right methods, without explicit inheritance — useful for decoupling code from concrete implementations while keeping static type checking.

Check your understanding

  1. 1. What happens if you instantiate an ABC subclass missing an abstractmethod implementation?

  2. 2. How does a class satisfy a `typing.Protocol`?

  3. 3. What is the benefit of coding against an abstract interface like ChainClient?