python 之class (Overriding methods)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值