第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

使用 Configparser 創(chuàng)建類的對象?

使用 Configparser 創(chuàng)建類的對象?

qq_遁去的一_1 2023-05-23 16:28:13
我對如何執(zhí)行此操作感到有些困惑。假設(shè)我有一個如下所示的 employees.ini 文件:[amber]sex=femaleage=29location=usaincome=60000debt=300[john]sex=maleage=19location=usaincome=19000debt=nan我有一個 for 循環(huán)來訪問每條信息并分配給一個變量。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 ...我希望現(xiàn)在能夠訪問 amber.foo 和 john.bar。但是,我正在努力研究如何在變量被循環(huán)的下一次迭代覆蓋之前將變量從 for 循環(huán)傳遞到類中。我覺得我可能想得太多了。我的想法是,這將使代碼更加用戶友好,因為大部分代碼可以保持不變,只有 .ini 需要在需要新用戶時更新。
查看完整描述

1 回答

?
qq_花開花謝_0

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


查看完整回答
反對 回復(fù) 2023-05-23
  • 1 回答
  • 0 關(guān)注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號