在PyCon 2015 上Raymond Hettinger 的演讲“超级考虑超级演讲super
”中,他解释了在多继承上下文中使用 Python 的优势。这是雷蒙德在演讲中使用的例子之一:
class DoughFactory(object):
def get_dough(self):
return 'insecticide treated wheat dough'
class Pizza(DoughFactory):
def order_pizza(self, *toppings):
print('Getting dough')
dough = super().get_dough()
print('Making pie with %s' % dough)
for topping in toppings:
print('Adding: %s' % topping)
class OrganicDoughFactory(DoughFactory):
def get_dough(self):
return 'pure untreated wheat dough'
class OrganicPizza(Pizza, OrganicDoughFactory):
pass
if __name__ == '__main__':
OrganicPizza().order_pizza('Sausage', 'Mushroom')
台下有人问雷蒙德,self.get_dough()
改用的区别super().get_dough()
。我不太了解 Raymond 的简短回答,但我编写了此示例的两个实现以查看差异。两种情况的输出相同:
Getting dough
Making pie with pure untreated wheat dough
Adding: Sausage
Adding: Mushroom
如果您将课程顺序从 using 更改OrganicPizza(Pizza, OrganicDoughFactory)
为OrganicPizza(OrganicDoughFactory, Pizza)
using self.get_dough()
,您将得到以下结果:
Making pie with pure untreated wheat dough
但是,如果您使用super().get_dough()
这是输出:
Making pie with insecticide treated wheat dough
我理解super()
雷蒙德解释的行为。但是self
在多重继承场景中的预期行为是什么?