Python Class Inheritance: Calling a function of a

2019-07-23 08:39发布

问题:

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"


标签: python class