1 回答

TA貢獻1835條經(jīng)驗 獲得超7個贊
我會添加一個類方法來將配置文件數(shù)據(jù)解析為一個新對象。
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 ...
現(xiàn)在,如何實際創(chuàng)建 的實例的細節(jié)User在類本身中被抽象掉了;遍歷配置的代碼只需要將相關(guān)數(shù)據(jù)傳遞給類方法即可。
from configparser import ConfigParser
config=ConfigParser()
config.read('employees.ini')
users = [User.from_config(section, config[section]) for section in config.sections()]
由于你的類使用配置文件的鍵名作為參數(shù)名,你可以直接解壓字典并使用__init__而不是定義類方法。
from configparser import ConfigParser
config=ConfigParser()
config.read('employees.ini')
users = [User(section, **config[section]) for section in config.sections()]
添加回答
舉報