Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extending class in python 2.7, usage of super()

Perhaps this is a silly question, but why doesn't this code work in python 2.7?

from ConfigParser import ConfigParser

class MyParser(ConfigParser):
    def __init__(self, cpath):
        super(MyParser, self).__init__()
        self.configpath = cpath
        self.read(self.configpath)

It fails on:

TypeError: must be type, not classobj

on the super() line.

like image 903
lollercoaster Avatar asked Aug 31 '25 20:08

lollercoaster


2 Answers

Most likely because ConfigParser does not inherit from object, hence, is not a new-style class. That's why super doesn't work there.

Check the ConfigParser definition and verify if it's like this:

class ConfigParser(object): # or inherit from some class who inherit from object

If not, that's the problem.

My advice to your code is not use super. Just invoke directly self on the ConfigParser like this:

class MyParser(ConfigParser):
    def __init__(self, cpath):
        ConfigParser.__init__(self)
        self.configpath = cpath
        self.read(self.configpath)
like image 164
Paulo Bu Avatar answered Sep 04 '25 01:09

Paulo Bu


The problem is that ConfigParser is an old-style class. super does not work with old-style classes. Instead, use explicit call to __init__:

def __init__(self, cpath):
     ConfigParser.__init__(self)
     self.configpath = cpath
     self.read(self.configpath)

See this question, for example, for an explanation of new vs old style classes.

like image 33
shx2 Avatar answered Sep 04 '25 03:09

shx2