为了账号安全,请及时绑定邮箱和手机立即绑定

是否有内置方法可以从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 关注
  • 107 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信