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

Python 2.x super __init__ inheritance doesn't work when parent doesn't inherit from object

我有下面的python 2.7代码:

1
2
3
4
5
6
7
8
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__()方法,这样当我实例化一个"眼睛"时,除了设置什么帧外,它还可以做一些其他的事情(self.some ou-other-defined ou-stufacture())。Frame.__init__()需要先运行。

我得到以下错误:

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

我不明白它的逻辑原因。有人能解释一下吗?我习惯用Ruby输入"super"。


这里有两个错误:

  • super()只适用于新型类;使用object作为Frame的基类,使其使用新型语义。

  • 您仍然需要用正确的参数调用被重写的方法;将image传递给__init__调用。

  • 所以正确的代码是:

    1
    2
    3
    4
    5
    6
    7
    8
    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()


    Frame必须扩展object,因为只有新的样式类支持super调用你在Eye中所做的如下:

    1
    2
    3
    4
    5
    6
    7
    8
    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()


    请在代码顶部写:__metaclass__ = type,这样我们就可以访问超级类了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    __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()


    嗨,看到我的python 2.7工作代码了吗?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    __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)