笑凡
2021-07-17 18:57
采纳率: 50%
浏览 33
已结题

python函数的参数赋值问题

python如何批量赋值?
我有这么个需求,一个python函数中有若干参数(**kwargs),这些参数需要用户输入,不输入的参数直接读取配置.

我怎么能一次取出没有给值的参数?好用这些参数去读取配置呢

img

  • 收藏

1条回答 默认 最新

  • vigiles 2021-07-17 22:34
    已采纳

    https://ask.csdn.net/questions/7475524 我感觉这里的那个专家给的回答很专业很直白了。我这里直接抄一遍吧

    from configparser import ConfigParser
    
    
    class KWargsDefValue:
    
        def __init__(self):
            self.name = None
            self.age = None
            self.phone = None
            self.address = None
            self.gender = None
            self.count = None
            self.config = ConfigParser()
        
        """ kwdv.ini文件内容
        [info1]
        address=china
        gender=man
        count=3334
        """
        def init_info(self, name=None, age=None, phone=None, **kwargs):
            # name、age、phone三个参数是否需要合并给kwargs
            self.name = name
            self.age = age
            self.phone = phone
            # 加载某些参数的默认值
            self.config.read('comm/kwdv.ini', encoding="utf-8")
            info = self.config.items('info1')
            infoDict = dict(info)
            infoDict.update(kwargs)
            self.address = infoDict.get("address")
            self.gender = infoDict.get("gender")
            self.count = infoDict.get("count")
    
        def __str__(self) :
            return "KWargsDefValue[name={}, age={}, phone={}, address={}, gender={}, count={}]".format(self.name, self.age, self.phone, self.address, self.gender, self.count)
    
    kwdv = KWargsDefValue()
    kwdv.init_info(age = 33, count=900)
    print(kwdv) # KWargsDefValue[name=None, age=33, age=None, phone=None, address=china, gender=man, count=900]
    
    
    打赏 评论

相关推荐 更多相似问题