Python 的 类型检查协议

等级 5387 次按键

这使用typing.Protocol和@runtime_checkable定义可在运行时检查的结构化子类型。

Python 代码

# 从typing导入Protocol和runtime_checkable
1from typing import Protocol, runtime_checkable
2
# 启用运行时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

Python 等级 5 的更多代码示例

← 返回 Python 打字练习