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

Python子类无需__init__访问父类变量与方法的问题及修复

无需__init__实现子类访问父类类属性与方法的修复方案

问题分析

当前代码存在两类问题:

  1. 语法拼写错误:main.py中的笔误会直接导致运行报错
  2. to_dict方法逻辑缺陷:原方法仅读取当前类的__dict__,未递归收集父类的类属性,导致子类调用to_dict时无法获取父类定义的a、b、c、d等值

第一步:修正main.py的语法错误

两处明显笔误:

  • a = SetupSetting.a 拼写错误,应为 a = SetupSettings.a(类名少了末尾的s)
  • teardown_settings = TeardownSettings.to_dict(). 多了末尾的点,应为 teardown_settings = TeardownSettings.to_dict()

第二步:修复to_dict方法,递归收集父类属性

继承的父类属性不会直接存放在子类的__dict__中(除非子类重写),因此需要遍历所有父类的属性并合并。修改后的config.py代码如下:

# 补充示例函数实现(实际根据业务逻辑编写)
def function_to_get_c_and_d_values():
    return "c_val", "d_val"

def get_f1():
    return "f1_val"

def get_h1():
    return "h1_val"

class CommonSettings:
    a = 'a'
    b = 'b'
    c, d = function_to_get_c_and_d_values()

    @classmethod
    def to_dict(cls):
        # 初始化字典,先递归收集所有父类的属性
        class_attrs = {}
        # 遍历当前类的所有父类(排除object基类)
        for base_cls in cls.__bases__:
            if base_cls is not object and hasattr(base_cls, "to_dict"):
                class_attrs.update(base_cls.to_dict())
        # 收集当前类的自定义属性,过滤魔法属性和to_dict方法
        current_cls_attrs = {
            k: v for k, v in cls.__dict__.items()
            if not (k.startswith('__') and k.endswith('__') or k == "to_dict")
        }
        # 合并父类与当前类属性(子类属性会覆盖父类同名属性)
        class_attrs.update(current_cls_attrs)
        return class_attrs

class SetupSettings(CommonSettings):
    e = 'e'
    f = 'f'
    f1 = get_f1()

class TeardownSettings(CommonSettings):
    g = 'g'
    h = 'h'
    h1 = get_h1()

验证修复效果

修改后的main.py运行示例:

from config import SetupSettings, TeardownSettings

# 直接访问父类类属性
a = SetupSettings.a
print(a)  # 输出: 'a'

# 获取包含父类+子类所有属性的字典
setup_settings = SetupSettings.to_dict()
print(setup_settings)
# 输出: {'a': 'a', 'b': 'b', 'c': 'c_val', 'd': 'd_val', 'e': 'e', 'f': 'f', 'f1': 'f1_val'}

teardown_settings = TeardownSettings.to_dict()
print(teardown_settings)
# 输出: {'a': 'a', 'b': 'b', 'c': 'c_val', 'd': 'd_val', 'g': 'g', 'h': 'h', 'h1': 'h1_val'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:17:28