使用Configparser创建类的对象?

问题描述

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

假设我有一个如下的employee.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。

感谢您能提供的任何帮助。

解决方法

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

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,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方法。

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()]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...