覆盖超类函数

时间:2013-11-10 22:53:15

标签: python class inheritance python-2.7

调用condition后,成员变量"new"应从"like new"更改为my_car.drive_car()。但是,此调用仍会执行drive_car超类而不是class Car

class ElectricCar函数
  • 我错过了什么吗?
  • 是否有更优雅的方式来覆盖 超类函数?


    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"

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

    print my_car.condition #Prints "New"
    my_car.drive_car()
    print my_car.condition #Prints "Used" instead of "Like New"

1 个答案:

答案 0 :(得分:0)

这种继承实际上是传统的“良好的面向对象编程”。虽然还有很多其他方法,但您已经使用的方法是最好的方法。