You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取类的已声明/类型化参数并编写属性类型输出函数?

实现类及其父类的类型化参数提取方法

完整解决方案代码

from inspect import get_annotations
from typing import get_args, get_origin, Any, Union

class Parent:
    parent_param: str
    parent_default: str | None = None

    def find_params_meta(self):
        params_meta = {}
        # 遍历当前类及所有父类的方法解析顺序,跳过最顶层的object类
        for cls in type(self).__mro__[:-1]:
            # 获取当前类的所有类型注解
            annotations = get_annotations(cls, eval_str=False)
            for name, annotation in annotations.items():
                # 过滤以"_"开头的私有成员
                if name.startswith('_'):
                    continue
                # 解析类型,处理Union(即 | 语法)的情况
                if get_origin(annotation) is Union:
                    types = list(get_args(annotation))
                else:
                    types = [annotation]
                # 将NoneType转换为断言要求的None
                types = [t if t is not type(None) else None for t in types]
                # 构建参数元数据
                meta = {"types": types}
                # 检查当前类是否定义了该成员的默认值(排除方法)
                if name in cls.__dict__ and not callable(cls.__dict__[name]):
                    meta["default"] = cls.__dict__[name]
                # 合并到结果,子类成员会覆盖父类同名成员
                params_meta[name] = meta
        return params_meta

class Child(Parent):
    child_param: str
    _params_meta: dict[str, Any] | None = None

    def __init__(self, parent_param: str, child_param: str):
        self._params_meta = self.find_params_meta()
        self.child_param = child_param
        self.parent_param = parent_param

assert Child("parent param", "child param")._params_meta == {
    "parent_param": {"types": [str]},
    "parent_default": {"types": [str, None], "default": None},
    "child_param": {"types": [str]},
}

关键解决思路

  • 获取未实例化的类参数:直接操作类对象而非实例,通过type(self).__mro__遍历当前类及所有父类,从类的注解(通过inspect.get_annotations安全获取)和__dict__中提取参数信息,避免调用getattr(self, name)触发AttributeError。
  • 收集父类的参数:利用MRO(方法解析顺序)遍历继承链上的所有类,逐个处理每个类的注解和默认值,确保父类的类型化参数被完整收集。
  • 过滤私有成员:遍历注解时直接跳过以_开头的成员名,排除私有属性和方法。
  • 解析类型与默认值:
    • 用typing.get_origin和get_args解析Union类型(Python 3.10+的|语法),拆分出所有子类型;
    • 将type(None)转换为断言要求的None;
    • 从类的__dict__中获取默认值,同时排除方法类型的成员,避免把类方法、实例方法误当成参数。

内容的提问来源于stack exchange,提问作者zalun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:15:06