Python Class Inheritance: Calling a function of a derivative class

一世执手 提交于 2019-12-24 17:18:31

问题


The my_car.drive_car() method is meant to update ElectricCar's member variable condition to "like new" but still calls drive_car from the Car super class.

    my_car = ElectricCar("Flux capacitor", "DeLorean", "silver", 88)

    print my_car.condition #Prints "New"
    my_car.drive_car()
    print my_car.condition #Prints "Used"; is supposed to print "Like New"

Am I missing something? Is there a more elegant way to override superclass functions?

class ElectricCar inherits from the super class Car

    class Car(object):
            condition = "new"

            def __init__(self, model, color, mpg):
                    self.model, self.color, self.mpg = model, color, mpg

            def drive_car(self):
                    self.condition = "used"

    class ElectricCar(Car):
            def __init__(self, battery_type, model, color, mpg):
                    self.battery_type = battery_type
                    super(ElectricCar, self).__init__(model, color, mpg)

            def drive_car(self):
                    self.condition = "like new"

回答1:


You're defining condition as a class variable instead of an instance variable. Do this:

class Car(object):
    def __init__(self, model, color, mpg):
        self.model, self.color, self.mpg = model, color, mpg
        self.condition = "new"

    def drive_car(self):
        self.condition = "used"

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        super(ElectricCar, self).__init__(model, color, mpg)
        self.battery_type = battery_type

    def drive_car(self):
        self.condition = "like new"


来源:https://stackoverflow.com/questions/19895772/python-class-inheritance-calling-a-function-of-a-derivative-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!