![](/img/trans.png)
[英]Can we call instance method of parent class from class method of child class in python 2.7?
[英]python 2.7 - how to call parent class constructor
我有下面的基类
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
我在扩展这个类,如下所示:
class Myfile(FileUtil):
def __init__(self, extension):
super(Myfile, self).__init__()
self.extension = 'text'
## other methods of class
但是我遇到错误了吗?
super(Myfile, self).__init__()
TypeError: super() takes at least 1 argument (0 given)
我浏览了许多文档,发现在2.x和3.x中调用super()有不同的方式。 我尝试了两种方式,但都出错了。
您有2个选择
旧样式类,则应直接调用super构造函数。
class FileUtil():
def __init__(self):
pass
class Myfile(FileUtil):
def __init__(self, extension):
FileUtil.__init__(self)
新样式类,从您的基类中的对象继承,并且您对super的当前调用将得到正确处理。
class FileUtil(object):
def __init__(self):
pass
class Myfile(FileUtil):
def __init__(self, extension):
super(Myfile, self).__init__()
您可能还需要使用super()
函数创建FileUtil
类:
class FileUtil(object):
def __init__(self):
super(FileUtil, self).__init__()
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.