Python知识分享网 - 专业的Python学习网站 学Python,上Python222
Python 3.11.4 官方文档 下载
匿名网友发布于:2025-05-21 11:40:19
(侵权举报)
(假如点击没反应,多刷新两次就OK!)

Python 3.11.4 官方文档 下载 图1

 

 

资料内容:

 

1 在 Python 3.10 以上版本中访问对象的注解字典
Python 3.10 在标准库中加入了一个新函数:inspect.get_annotations()。在 Python 3.10
以上的版本中,调用该函数就是访问对象注解字典的最佳做法。该函数还可以“解析”字符
串形式的注解。
有 时 会 因 为 某 些 原 因 看 不 到 inspect.get_annotations() , 也 可 以 直 接 访 问
__annotations__ 数据成员。这方面的最佳实践在 Python 3.10 中也发生了变化:从 Python
3.10 开始,Python 函数、类和模块的 o.__annotations__ 保证可用。如果确定是要查看这
三种对象,只要利用 o.__annotations__ 读取对象的注释字典即可。
不过其他类型的可调用对象可能就没有定义__annotations__属性,比如由functools.
partial() 创建的可调用对象。当访问某个未知对象的 “__annotations__“ 时,Python
3.10 以 上 版 本 的 最 佳 做 法 是 带 三 个 参 数 去 调 用 getattr() , 比 如 getattr(o,
'__annotations__', None)。
Before Python 3.10, accessing __annotations__ on a class that defines no annotations but that has
a parent class with annotations would return the parent’s __annotations__. In Python 3.10 and
newer, the child class’s annotations will be an empty dict instead.

 

2 在 Python 3.9 及更早的版本中访问对象的注解字典
在 Python 3.9 及之前的版本中,访问对象的注解字典要比新版本中复杂得多。这个是 Python

低版本的一个设计缺陷,特别是访问类的注解时。
要访问其他对象——函数、可调用对象和模块——的注释字典,最佳做法与 3.10 版本相同,
假定不想调用 inspect.get_annotations():你应该用三个参数调用 getattr() ,以
访问对象的 __annotations__ 属性。
不幸的是,对于类而言,这并不是最佳做法。因为 `__annotations__ 是类的可选属性,
并且类可以从基类继承属性,访问某个类的 __annotations__ 属性可能会无意间返回 基
类的注解数据