问题描述
我对如何执行此操作有些困惑。
[Amber]
sex=female
age=29
location=usa
income=60000
debt=300
[john]
sex=male
age=19
location=usa
income=19000
debt=nan
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()]