如何在python

时间:2018-07-03 03:39:15

标签: python inheritance method-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(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()

1 个答案:

答案 0 :(得分:0)

在这种情况下,对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