abc Blocks Incomplete Subclasses
Enforce interface contracts with abc: abstract methods raise TypeError at instantiation time when a subclass leaves one unimplemented.
Code
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def save(self, key, value):
...
@abstractmethod
def load(self, key):
...
# 只实现一个抽象方法的子类无法实例化:缺口在实例化时立刻暴露
class HalfStorage(Storage):
def save(self, key, value):
return True
try:
HalfStorage()
except TypeError as exc:
print('incomplete:', exc)
class MemoryStorage(Storage):
def __init__(self):
self.data = {}
def save(self, key, value):
self.data[key] = value
return True
def load(self, key):
return self.data.get(key)
store = MemoryStorage()
store.save('env', 'prod')
print('complete :', store.load('env'))Output
Captured from a sandboxed run of this snippet in the build pipeline.
incomplete: Can't instantiate abstract class HalfStorage with abstract method load
complete : prodHow it works
abc Blocks Incomplete Subclasses is built around the classes Storage, HalfStorage and MemoryStorage and the functions save, load and __init__.
Using it
The main signature reads def save(self, key, value)
Running the file prints labeled results such as incomplete:, complete : — each operation’s effect is visible in the output.
save is the public entry point; everything else in the file exists to support it.
Key statements
def save(self, key, value):
...
def save(self, key, value):
return True
def save(self, key, value):
self.data[key] = value
return True
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `abc`. The file defines `save`, `load`, `__init__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.