Abstract base classes
A protocol describes a shape from the outside. An abstract base class, or ABC, is a real parent class that subclasses must complete. Python refuses to create an instance while any abstract method is still missing.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): ...
def describe(self):
return f"area {self.area():.1f}"
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
print(Square(3).describe())
try:
Shape()
except TypeError as e:
print(e)- The error comes when the object is created, not later when the missing method is finally called.
- Ordinary methods such as
describeare inherited and may call the abstract ones. collections.abchas ABCs for containers. SubclassMapping, write__getitem__,__len__and__iter__, and you getget,keys,items,inand==for free.
Use an ABC when subclasses should share code and must fill in specific methods. Use a protocol when unrelated classes only need to match a shape.
Your task
Make Storage an abstract base class with abstract load(key) and save(key, value), keeping its concrete update(key, fn), which saves fn(old value) and returns it. MemoryStorage(Storage) keeps values in a dict, and its load raises KeyError for a missing key.
The explanation opens here once every check passes.