9-9 电瓶升级
1. 项目
在本节最后一个 electric_car.py 版本中,给 Battery 类添加一个名为
upgrade_battery()的方法。这个方法检查电瓶容量,如果它不是 85,就将它设置为 85。
创建一辆电瓶容量为默认值的电动汽车,调用方法 get_range(),然后对电瓶进行升级,
并再次调用 get_range()。你会看到这辆汽车的续航里程增加了。
2. 代码
class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + "miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class Battery(): """一次模拟电动汽车电瓶的简单尝试""" def __init__(self, battery_size = 70): """初始化电瓶的属性""" self.battery_size = battery_size def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-kWh battery.") 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): # 添加方法 self.battery_size = 85 # 设置电瓶大小为85 class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self, make, model, year): """初始化父类的属性,再初始化电动汽车特有的属性""" super().__init__(make, model, year) self.battery = Battery() # 把电瓶类作为电瓶车的属性 my_BYD = ElectricCar('BYD', '秦', 2012) # 创建默认值电瓶容量的车 my_BYD.battery.get_range() # 调用电瓶的方法 my_BYD.battery.upgrade_battery() # 调用电瓶的方法 my_BYD.battery.get_range()
3. 运行结果
D:\python编程:从入门到实践\venv\Scripts\python.exe "D:/python编程:从入门到实践/9-9 电瓶升级.py" This car can go approximately 240 miles on a full charge. This car can go approximately 270 miles on a full charge. Process finished with exit code 0