Python中如何获取类及其所有父类的注解?
获取Python类继承树中所有注解的通用方法
完全可行。你可以通过遍历类的方法解析顺序(MRO),依次收集每个父类(含自身)的注解并合并,就能得到继承树中所有类的注解集合。
实现代码
import inspect def get_all_annotations(cls): all_annotations = {} # 遍历类的方法解析顺序,覆盖自身及所有父类 for base_cls in inspect.getmro(cls): # 合并当前类的注解到结果字典 all_annotations.update(inspect.get_annotations(base_cls)) return all_annotations # 测试示例类 class parent(object): parent_annotation: str class child(parent): child_annotation: int # 调用函数获取全部注解 print(get_all_annotations(child)) # 输出结果: {'parent_annotation': <class 'str'>, 'child_annotation': <class 'int'>}
说明
inspect.getmro(cls)会返回类的MRO元组,顺序是子类→直接父类→顶层父类(示例中为child→parent→object)object类无自定义注解,不会影响最终结果- 若子类与父类存在同名注解,子类注解会覆盖父类的,这符合Python继承的重写逻辑
内容的提问来源于stack exchange,提问作者pgulley
相关产品推荐
相关产品推荐

