Python 2.x super __init__ 继承在父类未继承object时不起作用

29 投票
4 回答
48170 浏览
提问于 2025-04-18 03:01

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

我不太明白这个错误的逻辑原因。有人能帮我解释一下吗?我习惯在ruby里直接输入'super'。

4 个回答

-1

你好,看看我为Python 2.7写的工作代码

__metaclass__ = type
class Person:
    def __init__(self, first, last, age):
        self.firstname = first
        self.lastname = last
        self.age = age

    def __str__(self):
        return self.firstname + " " + self.lastname + ", " + str(self.age)

class Employee(Person):
    def __init__(self, first, last, age, staffnum):
        super(Employee, self).__init__(first, last, age)
        self.staffnumber = staffnum

    def __str__(self):
        return super(Employee, self).__str__() + ", " +  self.staffnumber


x = Person("Marge", "Simpson", 36)
y = Employee("Homer", "Simpson", 28, "1007")

print(x)
print(y)
0

请在代码的最上面写上:__metaclass__ = type,这样我们就可以访问父类了。

__metaclass__ = type
class Vehicle:
                def start(self):
                                print("Starting engine")
                def stop(self):
                                print("Stopping engine")                            
class TwoWheeler(Vehicle):
                def say(self):
                    super(TwoWheeler,self).start()
                    print("I have two wheels")
                    super(TwoWheeler,self).stop()                            
Pulsar=TwoWheeler()
Pulsar.say()
13

这里说的Frame必须要继承object,因为只有新式的类才能支持你在Eye里使用的super调用,像这样:

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()
53

这里有两个错误:

  1. super() 这个用法只适用于 新式类;为了让 Frame 使用新式类的特性,你需要把 object 作为它的基类。

  2. 你还需要用正确的参数来调用被重写的方法;在调用 __init__ 时要传入 image

所以正确的代码应该是:

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()

撰写回答