I want to extend SafeConfigParser with some functionality by inheriting from it:
class ExtendedConfigParser(SafeConfigParser):
def __init__(self, *args, **kwargs):
SafeConfigParser.__init__(self, *args, **kwargs)
..but have a problem with SafeConfigParser's 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? (note: it seems that SafeConfigParser is an old-style class).
I assume you're inheriting from Python's SafeConfigParser
and you're trying to instantiate ExtendedConfigParser
like this:
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.
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
. I'm assuming you're wanting to access config_file
only in ExtendedConfigParser
and not in SafeConfigParser
.
All you need to do is change your __init__
parameters in ExtendedConfigParser
:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.