当父级不从对象继承时,Python 2.x超级__init__继承不起作用

cjm2671:

我有以下Python 2.7代码:

class Frame:
    def __init__(self, image):
        self.image = image

class Eye(Frame):
    def __init__(self, image):
        super(Eye, self).__init__()
        self.some_other_defined_stuff()

我正在尝试扩展该__init__()方法,以便在实例化“ Eye”时,除了Frame设置的内容外,它还会执行很多其他操作(self.some_other_defined_stuff())。Frame.__init__()需要先运行。

我收到以下错误:

super(Eye, self).__init__()
TypeError: must be type, not classobj

这是我不明白的逻辑原因。有人可以解释一下吗?我习惯在红宝石中键入“ super”。

马丁·彼得斯(Martijn Pieters):

这里有两个错误:

  1. super()仅适用于新型类使用object的基类Frame,使之使用新型语义。

  2. 您仍然需要使用正确的参数来调用覆盖的方法。image接到__init__通话中。

因此正确的代码将是:

class Frame(object):
    def __init__(self, image):
        self.image = image

class Eye(Frame):
    def __init__(self, image):
        super(Eye, self).__init__(image)
        self.some_other_defined_stuff()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章