在本节最后一个electric_car.py版本中,给Battery 类添加一个名为upgrade_battery() 的方法。这个方法检查电瓶容量,如果它不是85,就将它 设置为85。创建一辆电瓶容量为默认值的电动汽车,调用方法get_range() ,然后对电瓶进行升级,并再次调用get_range() 。你会看到这辆汽车的续航里程增加了。 ?
#electric_car.py 最终版本
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)
#9-9新添加的方法
def upgrade_battery(self):
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 = Battery()
my_tesla = ElectricCar('tesla' , 'model s' , 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
print('\n------')
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()
结果
2016 Tesla Model S This car has a 70-KWH battery. 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
|