python 2.7-如何调用父类构造函数

vir*_*rus 1 python python-2.7

我有下面的基类

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
Run Code Online (Sandbox Code Playgroud)

我在扩展这个类,如下所示:

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

但是我遇到错误了吗?

super(Myfile, self).__init__()
TypeError: super() takes at least 1 argument (0 given)
Run Code Online (Sandbox Code Playgroud)

我浏览了许多文档,发现在2.x和3.x中调用super()有不同的方式。我尝试了两种方式,但都出错了。

Pau*_*ney 5

您有2个选择

旧样式类,则应直接调用super构造函数。

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

class Myfile(FileUtil):
    def __init__(self, extension):
        FileUtil.__init__(self)
Run Code Online (Sandbox Code Playgroud)

新样式类,从您的基类中的对象继承,并且您对super的当前调用将得到正确处理。

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

class Myfile(FileUtil):
    def __init__(self, extension):
        super(Myfile, self).__init__()
Run Code Online (Sandbox Code Playgroud)

  • @minitoto在他的代码类FileUtil:中,在我的代码类FileUtil(object)中: (2认同)