当父不从对象继承时,Python 2.x super __init__继承不起作用 [英] Python 2.x super __init__ inheritance doesn't work when parent doesn't inherit from object

查看:149
本文介绍了当父不从对象继承时,Python 2.x super __init__继承不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Python 2.7代码:

I have the following Python 2.7 code:

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 __()需要先运行。

I'm trying to extend the __init__() method so that when I instantiate an 'Eye' it does a bunch of other stuff (self.some_other_defined_stuff()), in addition to what Frame sets up. Frame.__init__() needs to run first.

我收到以下错误:

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

我不理解其合理原因。有人可以解释一下吗?我习惯只在红宝石中键入'super'。

Which I do not understand the logical cause of. Can someone explain please? I'm used to just typing 'super' in ruby.

推荐答案

这里有两个错误:


  1. super()仅适用于新式课程;使用 object 作为 Frame 的基类,使其使用新式语义。

  1. super() only works for new-style classes; use object as a base class for Frame to make it use new-style semantics.

您仍然需要使用正确的参数调用重写方法;将 image 传递给 __ init __ 电话。

You still need to call the overridden method with the right arguments; pass in image to the __init__ call.

所以正确的代码是:

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__继承不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆