Как сделать многоуровневое наследование и переопределение методов в Python - PullRequest
0 голосов
/ 03 июля 2018

Я пытался сделать переопределение методов и многоуровневое наследование в 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 голосов
/ 03 июля 2018

В этом случае вызовы 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
...