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

标签 python python-2.7 inheritance super new-style-class

我有以下 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”。

最佳答案

这里有两个错误:

  1. super() 仅适用于 new-style classes ;使用 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()

关于当父对象不从对象继承时,Python 2.x super __init__ 继承不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23117717/

相关文章:

python - 图像未出现在 django 2.1 的模板中

python - 如何为接受 csv 文件的函数编写单元测试?

python - 通过将元素添加到特殊位置来扩展列表

python - 我想检查输入是否是 python 代码

c++ - "Error: Unresolved external symbol"每当我使用纯虚函数时

python - 在 Intel Mac OS X 上将 PATH AMPL 求解器与 Pyomo 结合使用

python - 为什么 django 按错误的字段分组?注释()

python-2.7 - 从列表中执行 python 文件

java - Java中调用子类方法

Ruby 错误处理 : Rescuing Exceptions in Subclasses