如何解决是否有内置方法从Python所有基类中获取所有__annotations__?
我们内置了dir()
函数,用于获取在基类中定义的所有可用于类或实例的属性。
注释是否相同?我想拥有get_annotations()
函数,其功能如下:
def get_annotations(cls: type): ... # ?
class Base1:
foo: float
class Base2:
bar: int
class A(Base1,Base2):
baz: str
assert get_annotations(A) == {'foo': float,'bar': int,'baz': str}
解决方法
这应该可以解决问题,对吧?
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,'baz': str}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。