abc 模組標準化Python 早期無介面/抽象類機制,開發者常用「拋出 NotImplementedError」或「raise Exception」模擬,但無法在**實例化時**強制檢查,只能在調用時才報錯。Python 2.6+ 引入 abc 模組(Abstract Base Classes),提供 ABCMeta 元類與 @abstractmethod 裝飾器,實現編譯期/實例化期強制約束。
# 寫法 1:直接 pass(無任何提示)
class OldStyle:
def do_work(self): pass
# 寫法 2:拋出異常(運行時才發現)
class OldStyle2:
def do_work(self):
raise NotImplementedError("Subclass must implement do_work")
# 使用
o = OldStyle2()
o.do_work() # 只有調用時才報錯
abc.ABC + @abstractmethod
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self) -> str: ...
@abstractmethod
def legs(self) -> int: ...
def describe(self) -> str: # 普通方法可提供默認實現
return f"{self.__class__.__name__}: {self.sound()}, legs={self.legs()}"
class Dog(Animal):
def sound(self): return "Woof"
def legs(self): return 4
class Cat(Animal):
def sound(self): return "Meow"
# 故意不實現 legs
# 測試
dog = Dog()
print(dog.describe()) # Dog: Woof, legs=4
try:
cat = Cat() # TypeError: Can't instantiate abstract class Cat with abstract method legs
except TypeError as e:
print(e)
ABCMeta.__new__ 掃描抽象方法定義類時,元類收集所有被 @abstractmethod 標記的方法名,存入 __abstractmethods__(frozenset)。子類繼承時自動合併,僅當集合為空才允許實例化。
@abstractmethod 可疊加
class Base(ABC):
@abstractmethod
def foo(self): ...
class Middle(Base):
@abstractmethod
def bar(self): ...
class Concrete(Middle):
def foo(self): pass
def bar(self): pass # 必須實現所有
class Shape(ABC):
@property
@abstractmethod
def area(self) -> float: ...
@classmethod
@abstractmethod
def from_config(cls, config: dict): ...
@staticmethod
@abstractmethod
def validate(config: dict) -> bool: ...
class Circle(Shape):
def __init__(self, r): self.r = r
@property
def area(self): return 3.14 * self.r ** 2
@classmethod
def from_config(cls, cfg): return cls(cfg["radius"])
@staticmethod
def validate(cfg): return "radius" in cfg and cfg["radius"] > 0
**順序固定**:@property / @classmethod / @staticmethod 在外,**@abstractmethod 在內**。
@abstractclassmethod / @abstractstaticmethod(3.3+ 棄用)直接用組合裝飾器替代,見上例。
ABC 註冊虛擬子類
class PluginInterface(ABC):
@abstractmethod
def execute(self): ...
class ThirdPartyTool:
def execute(self): print("Running third-party")
PluginInterface.register(ThirdPartyTool) # 無需繼承
assert issubclass(ThirdPartyTool, PluginInterface)
assert isinstance(ThirdPartyTool(), PluginInterface)
tp = ThirdPartyTool()
tp.execute() # 正常調用
適用於無法修改第三方類源碼、但需納入類型檢查體系的場景。
from abc import ABC, abstractmethod
from importlib import import_module
from typing import Dict, Type
class Command(ABC):
name: str
@abstractmethod
def run(self, *args): ...
class CommandRegistry:
_commands: Dict[str, Type[Command]] = {}
@classmethod
def register(cls, cmd_class: Type[Command]):
cls._commands[cmd_class.name] = cmd_class
@classmethod
def get(cls, name: str) -> Command:
return cls._commands[name]()
# 自動發現插件
def load_plugins(pkg: str):
import pkgutil
for _, modname, _ in pkgutil.iter_modules([pkg]):
import_module(f"{pkg}.{modname}")
# plugins/hello.py
class HelloCommand(Command):
name = "hello"
def run(self, *args): print(f"Hello {args[0] if args else 'World'}!")
CommandRegistry.register(HelloCommand)
ABC:直接用 class Foo: __metaclass__ = ABCMeta(Py2 風格)在 Py3 失效,必須 class Foo(ABC)。@abstractmethod def foo(self): print("default") 仍強制子類覆寫。若想提供默認實現,**不要**加 @abstractmethod。@abstractmethod def _internal(self) 子類需實現同名私有方法,易混淆,建議用公共/受保護命名。abc 模組將「介面契約」從文檔/約定提升為語言級強制約束。現代 Python 專案(特別是框架、庫、插件系統)**應優先使用 ABC 定義核心介面**,配合類型提示(typing.Protocol 結構化子類型)構建健壯、可擴展的架構。