简体   繁体   English

向ConfigParser的__init__添加参数

[英]Adding arguments to __init__ of ConfigParser

I want to extend SafeConfigParser with some functionality by inheriting from it: 我想通过继承自SafeConfigParser扩展一些功能:

class ExtendedConfigParser(SafeConfigParser):

    def __init__(self, *args, **kwargs):
        SafeConfigParser.__init__(self, *args, **kwargs)

..but have a problem with SafeConfigParser's init: ..但是SafeConfigParser的init有问题:

    SafeConfigParser.__init__(self, *args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'config_file'

I could get around the problem by deleting added kw arguments from kwargs, but I wonder if there is a more elegant solution? 我可以通过从kwargs中删除添加的kw参数来解决该问题,但是我想知道是否有更优雅的解决方案? (note: it seems that SafeConfigParser is an old-style class). (注意:SafeConfigParser似乎是一个老式的类)。

I assume you're inheriting from Python's SafeConfigParser and you're trying to instantiate ExtendedConfigParser like this: 我假设您是从Python的SafeConfigParser继承而来的,您正在尝试实例化ExtendedConfigParser如下所示:

cfg_parser = ExtendedConfigParser(config_file='my_file.cfg')

If that's the case, then SafeConfigParser doesn't have any keyword argument named config_file which is where the error is coming from. 如果是这种情况,则SafeConfigParser不会有任何名为config_file关键字参数,而这正是错误的来源。

A function declaration in python allows you to specify arguments, keyword arguments, and then it allows unspecified arguments and keyword arguments through *args and **kwargs . python中的函数声明允许您指定参数,关键字参数,然后通过*args**kwargs允许未指定的参数和关键字参数 I'm assuming you're wanting to access config_file only in ExtendedConfigParser and not in SafeConfigParser . 我假设你想访问config_file ExtendedConfigParser不是SafeConfigParser

All you need to do is change your __init__ parameters in ExtendedConfigParser : 您需要做的就是在ExtendedConfigParser更改__init__参数:

class ExtendedConfigParser(SafeConfigParser):

    def __init__(config_file='', *args, **kwargs):
        self.config_file = config_file
        SafeConfigParser.__init__(self, *args, **kwargs)

This allows you specify any needed parameters for ExtendedConfigParser and then passes any additional parameters on to SafeConfigParser 's constructor. 这使您可以为ExtendedConfigParser指定任何所需的参数,然后将所有其他参数传递给SafeConfigParser的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM