在多继承中super()如何工作? 例如,我有两个 init ,我想通过super()发送args:
class LivingThings(object):
def __init__(self, age ,name):
self.name=name
self.age=age
def Print(self):
print('age: ', self.age)
print('name: ', self.name)
class Shape(object):
def __init__(self, shape):
self.shape=shape
def Print(self):
print(self.shape)
class Dog(LivingThings, Shape):
def __init__(self, breed, age , name, shape):
self.breed=breed
super().__init__(age , name)
super().__init__(shape)
def Print(self):
LivingThings.Print(self)
Shape.Print(self)
print('breed', self.breed)
但错误:
super().__init__(shape)
TypeError: __init__() missing 1 required positional argument: 'name'
但是此代码有效:
class Dog(LivingThings, Shape):
def __init__(self, breed, age , name, shape):
self.breed=breed
Shape.__init__(self, shape)
LivingThings.__init__(self,age ,name)
所以super()dosent在多重继承中工作?
答案 0 :(得分:4)
super
在多重继承中工作正常;事实上,这正是它的用途。但出于某种原因,你用不同的论点称它为两次;这不是它的工作原理。
调用一次。它调用方法解析顺序中的下一个方法。然后该方法的响应调用super,调用下一个方法。
请阅读Raymond Hettinger的经典文章Super considered super。