1

my_car.drive_car()方法旨在将ElectricCar的成员变量更新condition为但仍从超类"like new"调用。drive_carCar

    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"

我错过了什么吗?有没有更优雅的方法来覆盖超类函数?

class ElectricCar从超级继承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"
4

1 回答 1

0

您将条件定义为类变量而不是实例变量。做这个:

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"
于 2013-11-11T00:31:29.953 回答