赞
踩
9-9 电瓶升级:在本节最后一个electric_car.py版本中,给Battery类添加一个名为upgrade_battery()的方法。这个方法检查电瓶容量,如果它不是85,就将它设置为85。创建一辆电瓶容量为默认值的电动汽车,调用方法get_range(),然后对电瓶进行升级,并再次调用get_range()。你会看到这辆汽车的续航里程增加了。
- class Car():
- """一次模拟汽车的简单尝试"""
-
- def __init__(self,make,model,year):
- """初始化描述汽车的属性"""
- self.make = make
- self.model = model
- self.year = year
-
-
- class Battery():
- """一次模拟电动汽车电瓶的简单尝试"""
-
- def __init__(self,battery_size=70):
- """初始化电瓶的属性"""
- self.battery_size = battery_size
-
- def get_range(self):
- """打印一条信息,指出电瓶的续航里程"""
- if self.battery_size == 70:
- range = 240
- elif self.battery_size == 85:
- range = 270
-
- message = "This car can go approximately " + str(range)
- message += " miles on a full charge."
- print(message)
-
- def upgrade_battery(self):
- """将电瓶容量升级为85"""
- if self.battery_size != 85:
- self.battery_size = 85
-
-
- class ElectricCar(Car):
-
- def __init__(self,make,model,year):
- super().__init__(make,model,year)
- self.battery_size = Battery()
-
- my_tesla = ElectricCar('tesla', 'model s', 2016)
- my_tesla.battery_size.get_range()
- my_tesla.battery_size.upgrade_battery()
- my_tesla.battery_size.get_range()
-
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。