【发布时间】:2020-07-27 05:36:58
【问题描述】:
我在将函数从父类覆盖到子类时遇到问题...
在没有构造函数的情况下覆盖函数是否有技巧?
class Vehicle:
def get_wheels(self):
return -1
class Jeep(Vehicle):
def __init__(self):
super().__init__()
class Motorcycle(Vehicle):
def __init__(self):
super().__init__()
jeep = Jeep()
print("Jeep has", jeep.get_wheels(), "wheels")
motorcycle = Motorcycle()
print("Motorcycle has", motorcycle.get_wheels(), "wheels")
预期的输出应该是
Jeep has 4 wheels
Motorcycle has 2 wheels
父类应该只具有函数
【问题讨论】:
-
你从哪里知道吉普车有四个轮子?当数字 4 不在您的代码中时,您为什么期望输出?
-
由于子类没有覆盖
get_wheels,它们得到了只返回-1的超类版本。如果你把def get_wheels(self): return 4放在Jeep中,你就会得到你想要的。
标签: python class overriding parent-child