Python如何获取类继承体系中所有成员的类型注解?
获取派生类包含基类的所有类型注解
先看你的场景代码:
class Base: a: int class Derived(Base): b: int print(Derived.__annotations__)
运行后只会输出{'b': <class 'int'>},即使Python 3.10新增的inspect.get_annotations(Derived)也只会返回当前类显式定义的注解。要获取包含基类成员的所有注解,需要手动遍历类的方法解析顺序(MRO)来合并所有注解。
解决方案1:遍历MRO合并__annotations__
通过遍历类的__mro__属性,从顶层基类到当前类依次合并每个类的注解,确保派生类的注解能覆盖基类的同名注解:
def get_all_annotations(cls): all_annotations = {} # 反转MRO顺序,从最基础的object到当前类 for base in reversed(cls.__mro__): all_annotations.update(getattr(base, '__annotations__', {})) return all_annotations # 测试 class Base: a: int class Derived(Base): b: int print(get_all_annotations(Derived)) # 输出: {'a': <class 'int'>, 'b': <class 'int'>}
解决方案2:结合inspect.get_annotations处理延迟注解
如果代码使用了from __future__ import annotations,注解会以字符串形式存储,这时可以用inspect.get_annotations配合eval_str=True来解析:
import inspect def get_all_annotations(cls): all_annotations = {} for base in reversed(cls.__mro__): # 解析字符串形式的注解 annotations = inspect.get_annotations(base, eval_str=True) all_annotations.update(annotations) return all_annotations
说明
Python的内置注解机制(包括__annotations__和inspect.get_annotations)默认只返回当前类显式定义的注解,这是设计上的选择——避免自动引入多层继承中不必要的注解。要获取继承来的注解,必须手动遍历MRO并合并。
内容的提问来源于stack exchange,提问作者Michael Brocidiacono
相关产品推荐
相关产品推荐

