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() |
我正在尝试扩展
我得到以下错误:
1 2 | super(Eye, self).__init__() TypeError: must be type, not classobj |
号
我不明白它的逻辑原因。有人能解释一下吗?我习惯用Ruby输入"super"。
这里有两个错误:
您仍然需要用正确的参数调用被重写的方法;将
所以正确的代码是:
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() |
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() |
请在代码顶部写:
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) |