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

如何在父类ann中定义方法获取子类myAnn的__init__输入参数?

解决父类方法获取子类__init__输入参数字典的问题

问题分析

当前代码中,父类ann的getInitInpArgs方法只能获取父类自身__init__的参数,原因是inspect.currentframe().f_back指向的是父类__init__的调用帧,而非子类myAnn的__init__帧,最终导致inputArgs仅包含arg1。要实现需求,需要回溯栈帧找到子类__init__对应的调用上下文。

解决方案

修改父类的getInitInpArgs方法,遍历栈帧链定位到子类__init__的调用帧,再提取该帧的参数信息。可根据需求选择仅保留子类参数,或合并父类参数。

代码实现(包含子类+父类参数)

import inspect

class ann():
    def __init__(self, arg1):
        super(ann, self).__init__()
        self.getInitInpArgs()

    def getInitInpArgs(self):
        frame = inspect.currentframe().f_back
        # 遍历栈帧,定位子类__init__的调用帧
        while frame:
            if frame.f_code.co_name == '__init__' and frame.f_locals.get('self', None).__class__ == self.__class__:
                break
            frame = frame.f_back
        
        # 提取子类__init__参数
        args, _, _, values = inspect.getargvalues(frame)
        subclass_args = {arg: values[arg] for arg in args if arg != 'self'}
        
        # 提取父类__init__参数(可选,不需要可删除)
        parent_frame = inspect.currentframe().f_back
        parent_args, _, _, parent_values = inspect.getargvalues(parent_frame)
        parent_args_dict = {arg: parent_values[arg] for arg in parent_args if arg != 'self'}
        
        # 合并两类参数
        self.inputArgs = {**parent_args_dict, **subclass_args}

class myAnn(ann):
    def __init__(self, inputSize, outputSize):
        super(myAnn, self).__init__(4)

z1 = myAnn(40, 1)
print(z1.inputArgs)  # 输出: {'arg1': 4, 'inputSize': 40, 'outputSize': 1}

代码实现(仅子类参数)

若只需要子类__init__的参数,简化方法即可:

import inspect

class ann():
    def __init__(self, arg1):
        super(ann, self).__init__()
        self.getInitInpArgs()

    def getInitInpArgs(self):
        frame = inspect.currentframe().f_back
        # 遍历栈帧找到子类__init__的调用帧
        while frame:
            if frame.f_code.co_name == '__init__' and frame.f_locals.get('self', None).__class__ == self.__class__:
                break
            frame = frame.f_back
        
        args, _, _, values = inspect.getargvalues(frame)
        self.inputArgs = {arg: values[arg] for arg in args if arg != 'self'}

class myAnn(ann):
    def __init__(self, inputSize, outputSize):
        super(myAnn, self).__init__(4)

z1 = myAnn(40, 1)
print(z1.inputArgs)  # 输出: {'inputSize': 40, 'outputSize': 1}

关键说明

  • 通过遍历栈帧链,精准定位到子类__init__的调用上下文,确保获取的是子类参数。
  • 用frame.f_locals.get('self', None).__class__ == self.__class__判断当前帧是否属于实例所属的子类,避免误匹配其他类的__init__方法。
  • 合并参数时利用字典解包语法快速整合父类与子类的参数字典。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:27:47