Python知識(shí)分享網(wǎng) - 專業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
Python 3.11.4 官方文檔 下載
匿名網(wǎng)友發(fā)布于:2025-05-21 11:40:19
(侵權(quán)舉報(bào))
(假如點(diǎn)擊沒(méi)反應(yīng),多刷新兩次就OK!)

Python 3.11.4 官方文檔 下載 圖1

 

 

資料內(nèi)容:

 

1 在 Python 3.10 以上版本中訪問(wèn)對(duì)象的注解字典
Python 3.10 在標(biāo)準(zhǔn)庫(kù)中加入了一個(gè)新函數(shù):inspect.get_annotations()。在 Python 3.10
以上的版本中,調(diào)用該函數(shù)就是訪問(wèn)對(duì)象注解字典的最佳做法。該函數(shù)還可以“解析”字符
串形式的注解。
有 時(shí) 會(huì) 因 為 某 些 原 因 看 不 到 inspect.get_annotations() , 也 可 以 直 接 訪 問(wèn)
__annotations__ 數(shù)據(jù)成員。這方面的最佳實(shí)踐在 Python 3.10 中也發(fā)生了變化:從 Python
3.10 開始,Python 函數(shù)、類和模塊的 o.__annotations__ 保證可用。如果確定是要查看這
三種對(duì)象,只要利用 o.__annotations__ 讀取對(duì)象的注釋字典即可。
不過(guò)其他類型的可調(diào)用對(duì)象可能就沒(méi)有定義__annotations__屬性,比如由functools.
partial() 創(chuàng)建的可調(diào)用對(duì)象。當(dāng)訪問(wèn)某個(gè)未知對(duì)象的 “__annotations__“ 時(shí),Python
3.10 以 上 版 本 的 最 佳 做 法 是 帶 三 個(gè) 參 數(shù) 去 調(diào) 用 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 及更早的版本中訪問(wèn)對(duì)象的注解字典
在 Python 3.9 及之前的版本中,訪問(wèn)對(duì)象的注解字典要比新版本中復(fù)雜得多。這個(gè)是 Python

低版本的一個(gè)設(shè)計(jì)缺陷,特別是訪問(wèn)類的注解時(shí)。
要訪問(wèn)其他對(duì)象——函數(shù)、可調(diào)用對(duì)象和模塊——的注釋字典,最佳做法與 3.10 版本相同,
假定不想調(diào)用 inspect.get_annotations():你應(yīng)該用三個(gè)參數(shù)調(diào)用 getattr() ,以
訪問(wèn)對(duì)象的 __annotations__ 屬性。
不幸的是,對(duì)于類而言,這并不是最佳做法。因?yàn)?`__annotations__ 是類的可選屬性,
并且類可以從基類繼承屬性,訪問(wèn)某個(gè)類的 __annotations__ 屬性可能會(huì)無(wú)意間返回 基
類的注解數(shù)據(jù)