Subclassing ConfigParser question

Peter Otten __peter__ at web.de
Tue Nov 25 12:41:35 EST 2003


Roy H. Berger wrote:

> If I want to subclass ConfigParser and changed the optionxform method
> to not return things in lower case wouldn't I just need the following
> code in my subclasss module?
> 
> from ConfigParser import *
> 
> class MyConfigParser(ConfigParser):
> def __init__(self, defaults=None):
> ConfigParser.__init__(self, defaults)
> 
> def optionxform (self, optionstr):
> return optionstr
> 
> Or do I need to re-implement all of the methods of ConfigParser?
> Sorry -- haven't done much subclassing with python.

You need to reimplement only methods with changed behaviour - that's the
whole idea of inheritance. In the above example even the constructor is
superfluous:

import ConfigParser # import * is *bad*

class MyConfigParser(ConfigParser.ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

would suffice. There is of course no guarantee that other methods of
ConfigParser make assumptions about optionxform() that your modified method
does not hold. These you will have to detect with a properly designed test
suite.

Peter




More information about the Python-list mailing list