示例工程 14-metaclasses-class-creation
14-metaclasses-class-creation/03-minimal-abc/minimal_abc.py
"""演示 ABCMeta 与 abstractmethod 在实例化时拦截。"""
from __future__ import annotations
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
def describe(self) -> str:
return f"area={self.area():.1f}"
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side**2
def main() -> None:
try:
Shape() # type: ignore[abstract] # 演示运行时拦截
except TypeError as exc:
print(f"abstract type: {type(exc).__name__}")
print(f"mentions area: {'area' in str(exc)}")
square = Square(3)
print(f"square: {square.describe()}")
print(f"abstract methods: {Shape.__abstractmethods__}")
if __name__ == "__main__":
main()