我有以下 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__()
方法,以便当我实例化一个“眼睛”时,除了什么 Frame设置。 Frame.__init__()
需要先运行。
我收到以下错误:
super(Eye, self).__init__()
TypeError: must be type, not classobj
我不明白其中的逻辑原因。有人可以解释一下吗?我习惯于在 ruby 中输入“super”。
最佳答案
这里有两个错误:
super()
仅适用于 new-style classes ;使用object
作为Frame
的基类,使其使用新式语义。你仍然需要使用正确的参数调用被覆盖的方法;将
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()
关于当父对象不从对象继承时,Python 2.x super __init__ 继承不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23117717/