Using "super" when subclassing a python class that is not derived from "object" (old-style?)

I am playing with a subclass of OptionParser from the std optparser library module. (Python 2.5.2) When I try, I get an exception:

 TypeError: super() argument 1 must be type, not classobj 

Considering OptionParser , it is not inferred from object . So I added object as a parent class (shown below) and super working correctly.

 from optparse import OptionParser, Option class MyOptionParser(OptionParser, object): """Class to change """ def __init__(self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None, epilog=None, ): super(MyOptionParser, self).__init__(usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog, epilog) if __name__ == '__main__': """Run a quick test """ parser = MyOptionParser() parser.add_option("-t", "--test", type="string", dest="test") (options, args) = parser.parse_args() print "The test option is: %s" % options.test 

Can this be done right?

+4
python
source share
1 answer

Yes, I don’t understand why this will not work. You just need to add a couple of spaces right before this super call - since it is written right now, it is not part of your custom init method. In addition, the shortcut you might want to use is ** kwargs - you can do a kwargs key check in your method if that is what you want to do:

 class MyOptionParser(OptionParser, object): """Class to change """ def __init__(self, **kwargs): # You can limit kwargs keys here super(MyOptionParser, self).__init__(**kwargs) 
+5
source share

All Articles