如何解决使用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()]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。