使用 Configparser 创建 class 的对象?

Using Configparser to create objects of a class?

我对如何做到这一点有点困惑。

假设我有一个 employees.ini 文件,如下所示:

[amber]
sex=female
age=29
location=usa
income=60000
debt=300

[john]
sex=male
age=19
location=usa
income=19000
debt=nan

我有一个 for 循环来访问每条信息并分配给一个变量。

from configparser import ConfigParser
config=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,其中每个部分都可以作为一个对象接受:

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 循环传递到 class 中。我觉得我可能想多了。

我的想法是这会使代码更加用户友好,因为大部分代码可以保持不变,并且只有在需要新用户时才需要更新 .ini。

感谢您提供的任何帮助。

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

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 实例的细节在 class 本身中被抽象出来;遍历配置的代码只需要将相关数据传递给 class 方法。

from configparser import ConfigParser
config=ConfigParser()

config.read('employees.ini')
users = [User.from_config(section, config[section]) for section in config.sections()]

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

from configparser import ConfigParser
config=ConfigParser()

config.read('employees.ini')
users = [User(section, **config[section]) for section in config.sections()]