Python 的 类型检查协议
等级 5387 次按键
这使用typing.Protocol和@runtime_checkable定义可在运行时检查的结构化子类型。
Python 代码
# 从typing导入Protocol和runtime_checkable1from typing import Protocol, runtime_checkable2 # 启用运行时isinstance检查3@runtime_checkable# 定义指定所需方法的协议4class Drawable(Protocol): # 只有签名,方法体用...代替5 def draw(self) -> str: ...6 # 隐式实现协议的类7class Circle: # 实现draw方法8 def draw(self) -> str: # 返回描述字符串9 return "Drawing circle"10 # 另一个实现协议的类11class Square: # 实现draw方法12 def draw(self) -> str: # 返回描述字符串13 return "Drawing square"14 # 接受任何Drawable的函数15def render(shape: Drawable) -> None: # 调用draw并打印结果16 print(shape.draw())17 # 创建图形列表18shapes = [Circle(), Square()]# 迭代并渲染每个图形19for s in shapes: # isinstance只检查是否存在draw方法,不检查其签名20 if isinstance(s, Drawable): # 渲染图形21 render(s)运行结果
Drawing circle Drawing square
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Python 代码中需要输入的符号及其出现次数。
(× 11)× 11:× 10-× 4.× 4"× 4>× 4,× 3_× 2[× 1