本文主要是介绍9-9 电瓶升级,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在本节最后一个electric_car.py版本中,给Battery 类添加一个名为upgrade_battery() 的方法。这个方法检查电瓶容量,如果它不是85,就将它 设置为85。创建一辆电瓶容量为默认值的电动汽车,调用方法get_range() ,然后对电瓶进行升级,并再次调用get_range() 。你会看到这辆汽车的续航里程增 加了。
class Car:def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_descriptive_name(self):long_name = str(self.year) + " " + self.make.title()long_name += " " + self.model.title()return long_namedef read_odometer(self):print("This car has "+str(self.odometer_reading)+" on it.")def updated_odometer(self, mileage):if mileage >= self.odometer_reading:self.odometer_reading = mileageelse:print("You can't roll back on meter")def increment(self, miles):self.odometer_reading += milesclass Battery:def __init__(self, battery_size=70):self.battery_size = battery_sizeself.range = 0def describe_battery(self):print("This car has a "+str(self.battery_size)+"-KWh battery.")def get_range(self):if self.battery_size == 70:self.range = 240elif self.battery_size == 85:self.range = 270print("This car can go about "+str(self.range)+" miles on a full charge.")def upgrade_battery(self):if self.battery_size != 85:self.battery_size = 85class ElectricCar(Car):def __init__(self, make, model, year):super().__init__(make, model, year)self.battery = Battery()my_car = ElectricCar("tesla", "models", 2016)
my_car.battery.get_range()
my_car.battery.upgrade_battery()
my_car.battery.get_range()
这篇关于9-9 电瓶升级的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!