在多重继承中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()剂量工作在多重继承?
它会,如果你正确实施 - 没有超类使用超级,所以只有第一个被调用,并且他们有不同的签名。 – jonrsharpe
除了向这些'__init__'方法添加适当的'super()'调用外,还需要对它们进行更改以使它们都具有相同的调用签名。简单的方法是使用关键字参数的词典,如Daniel Roseman所链接的Raymond Hettinger文章中的“ColoredShape”示例所示。 –