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

Python如何继承Config类的实例参数与方法到Model1类中使用

实现方案

错误原因梳理

你之前的写法存在以下几个问题:

  • 子类继承Config后没有调用父类的构造方法,父类中加载配置文件、生成EXTRACTION和TRAINING属性的逻辑完全没有执行,自然拿不到对应的属性值
  • 子类__init__方法中定义的config参数是多余的,继承场景下不需要额外传入Config实例
  • 代码缩进不符合Python规范,类下的方法需要统一缩进4个空格,否则会直接触发语法错误
  • 原Config类中yaml.load未指定Loader参数,运行时会抛出安全警告甚至报错

方案1:继承方式实现(符合你要求的继承需求)

首先先补全Config类的依赖导入和参数修正:

# config/config_read.py
import os
import sys
import yaml

class Config: 
    def __init__(self, config_file='model.yml'):
        abs_path = os.path.join(os.path.dirname(__file__))
        project_path = os.path.join(abs_path, '..')
        config_folder = os.path.join(project_path, 'model_configs')
        config_full_path = os.path.join(config_folder, config_file)
        print(config_full_path)
        try: 
            with open(config_full_path, 'r', encoding='utf-8') as cfg_file:
                self.config = yaml.load(cfg_file, Loader=yaml.FullLoader)
        except FileNotFoundError as fe: 
            print("config not found")
            sys.exit(2)
        self.EXTRACTION = self.config['data_extraction']
        self.TRAINING = self.config['model_build']

之后写继承Config的Model1类:

from config.config_read import Config

class Model1(Config):
    # 若使用默认配置文件可以省略__init__方法,父类构造会自动执行
    def __init__(self, config_file='model.yml'):
        # 调用父类构造方法,执行配置加载逻辑
        super().__init__(config_file=config_file)
        # 直接继承父类生成的属性即可
        self.extraction = self.EXTRACTION
        self.training = self.TRAINING
    
    # 注意实例方法第一个参数必须是self
    def extract(self):
        # 此处可直接使用self.extraction、self.training做逻辑处理
        df = None
        return df

调用方式:

e = Model1()
# 以下属性均可正常读取
print(e.extraction)
print(e.EXTRACTION)
print(e.TRAINING)

方案2:组合方式实现(更推荐,耦合度更低)

如果不需要强依赖继承关系,更推荐用组合的方式传入配置实例,后续换配置类时改动更小:

from config.config_read import Config

class Model1:
    def __init__(self, config: Config):
        self.extraction = config.EXTRACTION
        self.training = config.TRAINING
    
    def extract(self):
        df = None
        return df

调用方式:

# 先初始化配置实例
cfg = Config()
# 传入Model1
e = Model1(cfg)
print(e.extraction)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 03:45:08