【发布时间】:2018-09-26 21:47:30
【问题描述】:
如以下示例所示,super() 在用于菱形继承时有一些奇怪的(至少对我而言)行为。
class Vehicle:
def start(self):
print("engine has been started")
class LandVehicle(Vehicle):
def start(self):
super().start()
print("tires are safe to use")
class WaterCraft(Vehicle):
def start(self):
super().start()
print("anchor has been pulled up")
class Amphibian(LandVehicle, WaterCraft):
def start(self):
# we do not want to call WaterCraft.start, amphibious
# vehicles don't have anchors
LandVehicle.start(self)
print("amphibian is ready for travelling on land")
amphibian = Amphibian()
amphibian.start()
以上代码产生以下输出:
engine has been started
anchor has been pulled up
tires are safe to use
amphibian is ready for travelling on land
当我调用super().some_method() 时,我绝不会期望调用同一继承级别的类的方法。因此,在我的示例中,我不希望 anchor has been pulled up 出现在输出中。
调用super() 的类甚至可能不知道最终调用其方法的另一个类。在我的示例中,LandVehicle 甚至可能不知道 WaterCraft。
这种行为是否正常/预期?如果是,其背后的基本原理是什么?
【问题讨论】:
-
这种行为是 Python 的
super的重点。 (是的,这个名字很混乱。) -
所以我不应该使用
super来调用基类方法?那有什么好处呢,为什么还能顺着继承链下去呢? -
This 在技术上是重复的,但我既不喜欢问题也不喜欢答案。我认为我们可以做得更好。
-
如果
Amphibian没有锚,那么它不应该从WaterCraft继承,或者WaterCraft应该允许可选 锚。
标签: python python-3.x inheritance super diamond-problem