Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 2.7 - how to call parent class constructor

I have base class like below

class FileUtil:
    def __init__(self):
        self.outFileDir = os.path.join(settings.MEDIA_ROOT,'processed')
        if not os.path.exists(outFileDir):
            os.makedirs(outFileDir)
    ## other methods of the class

and I am extending this class as below:

class Myfile(FileUtil):
    def __init__(self, extension):
        super(Myfile, self).__init__()
        self.extension = 'text'
    ## other methods of class

But i am getting below error?

super(Myfile, self).__init__()
TypeError: super() takes at least 1 argument (0 given)

I gone through many documents and found that there are different sytex of calling super() in 2.x and 3.x. I tried both ways but getting error.

like image 684
Gaurav Pant Avatar asked Sep 08 '25 01:09

Gaurav Pant


1 Answers

You have 2 options

old style class, you should call the super constructor directly.

class FileUtil():
    def __init__(self):
        pass

class Myfile(FileUtil):
    def __init__(self, extension):
        FileUtil.__init__(self)

new style class, inherit from object in your base class and your current call to super will be processed correctly.

class FileUtil(object):
    def __init__(self):
        pass

class Myfile(FileUtil):
    def __init__(self, extension):
        super(Myfile, self).__init__()
like image 74
Paul Rooney Avatar answered Sep 10 '25 00:09

Paul Rooney