Overriding methods
Since our ElectricCar is a more specialized type of Car, we can give the ElectricCar its own drive_car() method that has different functionality than the original Car class’s.
题目:
Inside ElectricCar add a new method drive_car() that changes the car’s condition to the string “like new”.
Then, outside of ElectricCar, print the condition of my_car
Next, drive my_car by calling the drive_car() function
Finally, print the condition of my_car again
code :
class Car(object):
**condition = "new"** ##父类里定义的condition
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car (self):
return "This is a %s %s with %s MPG." %(self.color,self.model,str(self.mpg))
def drive_car (self):
self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition
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):** ##其实,这里有个疑问,为什么在这里,不需要再次定义下condition这个变量了呢?而init里,不是定义了所有的变量吗?
self.condition = "like new"
my_car = ElectricCar ("molten salt","silver","DeLorean",88)
print my_car.condition #这里本人也常会弄错,要弄清楚什么时候调用的是函数,什么时候是调用的里面的变量
my_car.drive_car()
print my_car.condition
结果显示:
new
used
new
like new