我們有內置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}
添加回答
舉報
0/150
提交
取消