Python 的 类型守卫模式

等级 5508 次按键

这使用TypeGuard创建类型缩小函数,以便更安全地处理联合类型。

Python 代码

# 导入用于类型提示的TypeGuard(Python 3.10+)和Union
1from typing import TypeGuard, Union
2
# class Cat 定义具有 meow 方法的猫
3class Cat:
# meow 返回猫叫声
4 def meow(self) -> str:
5 return "Meow!"
6
# class Dog 定义具有 bark 方法的狗
7class Dog:
# bark 返回狗叫声
8 def bark(self) -> str:
9 return "Woof!"
10
# is_cat 是 Cat 的类型守卫函数
11def is_cat(animal: Union[Cat, Dog]) -> TypeGuard[Cat]:
# 如果 animal 是 Cat 返回 True,缩小类型
12 return isinstance(animal, Cat)
13
# is_dog 是 Dog 的类型守卫函数
14def is_dog(animal: Union[Cat, Dog]) -> TypeGuard[Dog]:
# 如果 animal 是 Dog 返回 True,缩小类型
15 return isinstance(animal, Dog)
16
# make_sound 使用类型守卫进行安全的方法调用
17def make_sound(animal: Union[Cat, Dog]) -> str:
# is_cat 检查后,类型检查器知道 animal 是 Cat
18 if is_cat(animal):
# 可以安全地在 Cat 上调用 meow()
19 return animal.meow()
# is_dog 检查后,类型检查器知道 animal 是 Dog
20 elif is_dog(animal):
# 可以安全地在 Dog 上调用 bark()
21 return animal.bark()
# 未知类型的后备
22 return "Unknown"
23
# 用 Cat 实例测试
24print(make_sound(Cat()))
# 用 Dog 实例测试
25print(make_sound(Dog()))

运行结果

Meow!
Woof!
用这段代码练习打字

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

这段代码中的符号

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

  • (× 17
  • )× 17
  • :× 12
  • _× 7
  • ,× 6
  • "× 6
  • -× 5
  • [× 5
  • ]× 5
  • >× 5

Python 等级 5 的更多代码示例

← 返回 Python 打字练习