如何在python中进行多级继承和方法重写
我尝试在Python中执行方法重写和多级继承,但在以下代码中出现了一些错误:-如何在python中进行多级继承和方法重写,python,inheritance,overriding,Python,Inheritance,Overriding,我尝试在Python中执行方法重写和多级继承,但在以下代码中出现了一些错误:- class Car(object): def __init__(self): print("You just created the car instance") def drive(self): print("Car started...") def stop(self): print("Car stopped") class BMW(
class Car(object):
def __init__(self):
print("You just created the car instance")
def drive(self):
print("Car started...")
def stop(self):
print("Car stopped")
class BMW(Car):
def __init__(self):
super().__init__()
print("You just created the BMW instance")
def drive(self):
super(Car, self).drive()
print("You are driving a BMW, Enjoy...")
def headsup_display(self):
print("This is a unique feature")
class BMW320(BMW):
def __init__(self):
super().__init__()
print("You created BMW320 instance")
def drive(self):
super(BMW, self).drive()
print("You are enjoying BMW 320")
c = Car()
c.drive()
c.stop()
b = BMW()
b.drive()
b.stop()
b.headsup_display()
b320=BMW320()
b320.drive()
在这种情况下,对
super
的调用不需要参数:
class Car(object):
def __init__(self):
print("You just created the car instance")
def drive(self):
print("Car started...")
def stop(self):
print("Car stopped")
class BMW(Car):
def __init__(self):
super().__init__()
print("You just created the BMW instance")
def drive(self):
super().drive()
print("You are driving a BMW, Enjoy...")
def headsup_display(self):
print("This is a unique feature")
class BMW320(BMW):
def __init__(self):
super().__init__()
print("You created BMW320 instance")
def drive(self):
super().drive()
print("You are enjoying BMW 320")
c = Car()
c.drive()
c.stop()
b = BMW()
b.drive()
b.stop()
b.headsup_display()
b320 = BMW320()
b320.drive()
输出:
You just created the car instance
Car started...
Car stopped
You just created the car instance
You just created the BMW instance
Car started...
You are driving a BMW, Enjoy...
Car stopped
This is a unique feature
You just created the car instance
You just created the BMW instance
You created BMW320 instance
Car started...
You are driving a BMW, Enjoy...
You are enjoying BMW 320