示例工程 11-protocols-generics-overloads
11-protocols-generics-overloads/01-protocol-duck-typing/protocol_duck_typing.py
"""演示 Protocol 的结构化子类型,以及 runtime_checkable 只看名字。"""
from __future__ import annotations
from typing import Protocol, runtime_checkable
@runtime_checkable
class Shape(Protocol):
"""任何有 area() 的对象都算 Shape,不需要继承。"""
def area(self) -> float: ...
class Circle:
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return 3.14159 * self.radius**2
class Fake:
"""有 area 属性,但不是可调用方法。"""
area = 3.0
def total_area(shapes: list[Shape]) -> float:
return sum(shape.area() for shape in shapes)
def main() -> None:
circle = Circle(2.0)
fake = Fake()
print(f"circle isinstance: {isinstance(circle, Shape)}")
print(f"fake isinstance: {isinstance(fake, Shape)}")
print(f"fake area type: {type(fake.area).__name__}")
method_name = "area"
try:
getattr(fake, method_name)()
except TypeError as exc:
print(f"fake call error: {exc}")
print(f"total: {round(total_area([circle]), 2)}")
if __name__ == "__main__":
main()