为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Configparser 创建类的对象?

使用 Configparser 创建类的对象?

qq_遁去的一_1 2023-05-23 16:28:13
我对如何执行此操作感到有些困惑。假设我有一个如下所示的 employees.ini 文件:[amber]sex=femaleage=29location=usaincome=60000debt=300[john]sex=maleage=19location=usaincome=19000debt=nan我有一个 for 循环来访问每条信息并分配给一个变量。from configparser import ConfigParserconfig=ConfigParser()config.read('employees.ini')for section in config.sections():    name=section    sex=config[section]['sex']    age=config[section]['age']    location=config[section]['location']    income=config[section]['income']    debt=config[section]['debt']我还有一个类,其中每个部分都可以作为一个对象接受:class Users:    def __init__(self, name, sex, age, location, debt):        self.__name=name        self.__sex=sex        self.__age=age        self.__location=location        self.__income=income        self.__debt=debt    def foo(self):        do a thing    def bar(self):        do a different thing ...我希望现在能够访问 amber.foo 和 john.bar。但是,我正在努力研究如何在变量被循环的下一次迭代覆盖之前将变量从 for 循环传递到类中。我觉得我可能想得太多了。我的想法是,这将使代码更加用户友好,因为大部分代码可以保持不变,只有 .ini 需要在需要新用户时更新。
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

我会添加一个类方法来将配置文件数据解析为一个新对象。


class User:

    def __init__(self, name, sex, age, location, debt):

        self.__name=name

        self.__sex=sex

        self.__age=age

        self.__location=location

        self.__income=income

        self.__debt=debt


    @classmethod

    def from_config(cls, name, config):

        return cls(name, config['sex'], config['age'], config['location'], config['debt']


    def foo(self):

        do a thing


    def bar(self):

        do a different thing ...

现在,如何实际创建 的实例的细节User在类本身中被抽象掉了;遍历配置的代码只需要将相关数据传递给类方法即可。


from configparser import ConfigParser

config=ConfigParser()


config.read('employees.ini')

users = [User.from_config(section, config[section]) for section in config.sections()]

由于你的类使用配置文件的键名作为参数名,你可以直接解压字典并使用__init__而不是定义类方法。


from configparser import ConfigParser

config=ConfigParser()


config.read('employees.ini')

users = [User(section, **config[section]) for section in config.sections()]


查看完整回答
反对 回复 2023-05-23
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信