27

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

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.

I get the following error:

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

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

4

4 回答 4

50

这里有两个错误:

  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()
于 2014-04-16T18:47:43.743 回答
12

Frame必须扩展object,因为只有新样式类支持super您进行的调用,Eye如下所示:

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()
于 2014-04-16T18:48:40.717 回答
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()
于 2018-11-29T06:26:18.383 回答
-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)
于 2018-01-13T05:40:53.287 回答