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

cjm*_*671 25 python inheritance super new-style-class python-2.7

我有以下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()
Run Code Online (Sandbox Code Playgroud)

我正在尝试扩展该__init__()方法,以便当我实例化一个'Eye'时,除了Frame设置之外,还会做一堆其他的东西(self.some_other_defined_stuff()).Frame.__init__()需要先跑.

我收到以下错误:

super(Eye, self).__init__()
TypeError: must be type, not classobj
Run Code Online (Sandbox Code Playgroud)

其中我不明白其逻辑原因.有人可以解释一下吗?我习惯于在红宝石中输入'super'.

Mar*_*ers 46

这里有两个错误:

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


myu*_*uf3 12

Frame必须扩展,object因为只有新的样式类支持superEye这样做的调用:

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

  • @MartijnPieters认真的呵呵?无论如何固定. (2认同)