Python类继承:调用派生类的函数 [英] Python Class Inheritance: Calling a function of a derivative class
本文介绍了Python类继承:调用派生类的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
my_car.drive_car()
方法用于更新 ElectricCar
的成员变量条件
到like new
,但仍从 drive_car
c> Car 超级类。
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?
类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"
推荐答案
的实例变量。执行以下操作:
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类继承:调用派生类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文