亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Configparser 創建類的對象?

使用 Configparser 創建類的對象?

qq_遁去的一_1 2023-05-23 16:28:13
我對如何執行此操作感到有些困惑。假設我有一個如下所示的 employees.ini 文件:[amber]sex=femaleage=29location=usaincome=60000debt=300[john]sex=maleage=19location=usaincome=19000debt=nan我有一個 for 循環來訪問每條信息并分配給一個變量。from configparser import ConfigParserconfig=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 需要在需要新用戶時更新。
查看完整描述

1 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

我會添加一個類方法來將配置文件數據解析為一個新對象。


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


查看完整回答
反對 回復 2023-05-23
  • 1 回答
  • 0 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號