隐藏页面特效

typing模块中Protocol协议的使用

1|0说明


Python typing 模块中,Protocol 是一个用于定义协议(Protocol)的类。 协议是一种形式化的接口,定义了一组方法或属性的规范,而不关心具体的实现。Protocol 类提供了一种方式来定义这些协议。 使用 Protocol 类时,可以定义一个类,继承自 Protocol 并在类中定义需要的方法或属性。 这样,通过继承 Protocol,可以告诉静态类型检查器,该类遵循了特定的协议。 有点类似go语言中的interface,但又有所不同,感觉Protocol只是为了解决静态类型检查的问题

2|0示例


from typing import Protocol # 理解为定义接口及接口中的方法 class Animal(Protocol): def speak(self) -> str: pass def eat(self) -> str: pass # 实现类,dog实现了接口中的全部方法 class Dog: def speak(self) -> str: return "Woof!" def eat(self) -> str: return "Dog is eating hotdog" # 实现类,但是cat只实现了接口中的一个方法 class Cat: def speak(self) -> str: return "Meow!" # 参数为接口类型 def make_sound(animal: Animal) -> str: return animal.speak() dog = Dog() cat = Cat() # 如果单独运行,是没有问题的,所以你需要用mypy检查工具运行该代码 print(make_sound(dog)) # Output: Woof! print(make_sound(cat)) # Output: Meow! # mypy类型检查会提示如下报错,表示Cat类没有实现接口中的eat方法 part3.py:33: error: Argument 1 to "make_sound" has incompatible type "Cat"; expected "Animal" [arg-type] part3.py:33: note: "Cat" is missing following "Animal" protocol member: part3.py:33: note: eat

3|0示例2


from typing import Protocol, Any, TypeVar, TYPE_CHECKING from collections.abc import Iterable from typing_extensions import reveal_type # 定义接口,需要实现可以比较的__lt__方法 class SupportsLessThan(Protocol): def __lt__(self, other: Any) -> bool: ... LT = TypeVar('LT', bound=SupportsLessThan) # 表示泛型上限为SupportsLessThan def top(series: Iterable[LT], length: int) -> list[LT]: # 返回值也可以用LT,因为list也实现了__lt__方法 ordered = sorted(series, reverse=True) return ordered[:length] if __name__ == '__main__': fruit = 'mango pear apple kiwi banana'.split() # tuple实现了__lt__方法 series: Iterable[tuple[int, str]] = ( (len(s), s) for s in fruit ) length = 3 expected = [(6, 'banana'), (5, 'mango'), (5, 'apple')] result = top(series, length) # 所以可以将series传递到top中 TYPE_CHECKING = True if TYPE_CHECKING: reveal_type(series) reveal_type(expected) reveal_type(result) print(result == expected)

__EOF__

本文作者404 Not Found
本文链接https://www.cnblogs.com/weiweivip666/p/17502014.html
关于博主:可能又在睡觉
版权声明:转载请注明出处
声援博主:如果看到我睡觉请喊我去学习
posted @   我在路上回头看  阅读(1419)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
历史上的今天:
2022-06-25 自定义字典类
2022-06-25 擅长使用iter
点击右上角即可分享
微信分享提示