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

在Python类中使用configparser:如何动态访问类属性的名称与值

解决INI配置类手动维护字段的重复工作问题

当前实现的FolderLeftSettings类存在扩展性问题:每次在__init__中新增配置字段后,都需要手动修改write_to_ini和read_from_ini方法添加对应读写逻辑,重复工作量大且容易遗漏。以下是两种优化方案:


优化方案一:自动遍历实例属性(灵活型)

新增配置字段只需在__init__中直接定义,无需修改其他方法:

import configparser

config = configparser.ConfigParser()    
configfile = 'RealGui.ini'
      
class FolderLeftSettings:
    def __init__(self):
        self.name = "SECTION"
        # 直接定义配置字段及默认值
        self.last_directory = ""
        self.row_size = 6
        self.column_size = 9
        # 定义不需要序列化到INI的属性
        self.exclude_fields = {'name', 'exclude_fields'}

    def write_to_ini(self):
        if not config.has_section(self.name):
            config.add_section(self.name)
        with open(configfile, 'w') as f:
            # 遍历所有非排除属性,自动写入配置
            for attr_name, attr_val in self.__dict__.items():
                if attr_name not in self.exclude_fields:
                    config.set(self.name, attr_name, str(attr_val))
            config.write(f)

    def read_from_ini(self):
        # 提前记录每个配置字段的类型,用于读取时转换
        field_types = {
            attr_name: type(attr_val) 
            for attr_name, attr_val in self.__dict__.items() 
            if attr_name not in self.exclude_fields
        }
        try:
            config.read(configfile)
            if config.has_section(self.name):
                # 自动读取并转换每个字段
                for attr_name, convert_type in field_types.items():
                    if attr_name in config[self.name]:
                        setattr(self, attr_name, convert_type(config[self.name][attr_name]))
        except Exception as e:
            print("读取INI失败....将使用默认值覆盖")
            print(e)
            self.write_to_ini()

settings = FolderLeftSettings()

说明:

  • exclude_fields集合用于排除不需要写入INI的属性(如section名称name)
  • 写入时自动遍历实例属性,跳过排除项后写入配置
  • 读取时根据初始化时的字段类型自动转换配置值,无需手动指定转换逻辑

优化方案二:显式维护字段映射(可控型)

通过字典集中管理字段的默认值和类型,更精确控制配置逻辑:

import configparser

config = configparser.ConfigParser()    
configfile = 'RealGui.ini'
      
class FolderLeftSettings:
    def __init__(self):
        self.name = "SECTION"
        # 显式定义配置字段:键为属性名,值为(默认值, 类型转换函数)
        self.config_fields = {
            'last_directory': ('', str),
            'row_size': (6, int),
            'column_size': (9, int)
        }
        # 自动初始化默认值
        for key, (default_val, _) in self.config_fields.items():
            setattr(self, key, default_val)

    def write_to_ini(self):
        if not config.has_section(self.name):
            config.add_section(self.name)
        with open(configfile, 'w') as f:
            # 遍历配置字段自动写入
            for key, (_, _) in self.config_fields.items():
                config.set(self.name, key, str(getattr(self, key)))
            config.write(f)

    def read_from_ini(self):
        try:
            config.read(configfile)
            if config.has_section(self.name):
                # 遍历配置字段自动读取并转换类型
                for key, (_, type_convert) in self.config_fields.items():
                    if key in config[self.name]:
                        setattr(self, key, type_convert(config[self.name][key]))
        except Exception as e:
            print("读取INI失败....将使用默认值覆盖")
            print(e)
            self.write_to_ini()

settings = FolderLeftSettings()

说明:

  • config_fields字典集中管理所有配置字段的默认值和类型转换规则
  • 初始化时自动给属性赋值默认值,无需手动逐个定义
  • 读写逻辑完全基于config_fields,新增字段只需修改这个字典即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:15:58