使用 Configparser 创建类的对象?

我对如何执行此操作感到有些困惑。


假设我有一个如下所示的 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 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 需要在需要新用户时更新。


qq_遁去的一_1
浏览 89回答 1
1回答

qq_花开花谢_0

我会添加一个类方法来将配置文件数据解析为一个新对象。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 ConfigParserconfig=ConfigParser()config.read('employees.ini')users = [User.from_config(section, config[section]) for section in config.sections()]由于你的类使用配置文件的键名作为参数名,你可以直接解压字典并使用__init__而不是定义类方法。from configparser import ConfigParserconfig=ConfigParser()config.read('employees.ini')users = [User(section, **config[section]) for section in config.sections()]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python