Python 的 协议类型

等级 5298 次按键

这使用Protocol进行结构子类型化。类不需要继承Protocol,只需实现所需的方法。

Python 代码

# 从typing模块导入Protocol
1from typing import Protocol
2
# 定义带有必需方法签名的协议
3class Drawable(Protocol):
# 只有方法签名,没有实现
4 def draw(self) -> str: ...
5
# Circle类实现draw方法
6class Circle:
# draw方法的实现
7 def draw(self) -> str:
# 返回描述形状的字符串
8 return "Drawing circle"
9
# Square类实现draw方法
10class Square:
# draw方法的实现
11 def draw(self) -> str:
# 返回描述形状的字符串
12 return "Drawing square"
13
# 函数接受任何Drawable协议的实现者
14def render(shape: Drawable) -> None:
# 调用draw方法并打印结果
15 print(shape.draw())
16
# 渲染圆形:Circle有draw(),所以可行
17render(Circle())
# 渲染正方形:Square有draw(),所以可行
18render(Square())

运行结果

Drawing circle
Drawing square
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • (× 11
  • )× 11
  • :× 8
  • -× 4
  • .× 4
  • "× 4
  • >× 4

Python 等级 5 的更多代码示例

← 返回 Python 打字练习