亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否有內置方法可以從Python中的所有基類獲取所有__annotations__?

是否有內置方法可以從Python中的所有基類獲取所有__annotations__?

溫溫醬 2023-10-31 14:10:50
我們有內置dir()函數來獲取在基類中定義的類或實例可用的所有屬性。注釋也一樣嗎?我想要get_annotations()一個功能,其工作原理如下:def get_annotations(cls: type): ...  # ?class Base1:    foo: floatclass Base2:    bar: intclass A(Base1, Base2):    baz: strassert get_annotations(A) == {'foo': float, 'bar': int, 'baz': str}
查看完整描述

1 回答

?
陪伴而非守候

TA貢獻1757條經驗 獲得超8個贊

這應該可以解決問題,對吧?


def get_annotations(cls: type):

    all_ann = [c.__annotations__ for c in cls.mro()[:-1]]

    all_ann_dict = dict()

    for aa in all_ann[::-1]:

        all_ann_dict.update(**aa) 

return all_ann_dict


get_annotations(A)

# {'bar': int, 'foo': float, 'baz': str}

或者它的單行版本:


get_annotations = lambda cls: {k:v for c in A.mro()[:-1][::-1] for k,v in c.__annotations__.items()}


get_annotations(A)

# {'bar': int, 'foo': float, 'baz': str}


查看完整回答
反對 回復 2023-10-31
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號