#author = ‘zhanghang‘#coding :-*- utf-8 -*- class Car():#定义car类 def __init__(self,make,model,year): "初始化描述汽车的属性" self.make = make self.model = model self.year = year self.odometer_reading = 0 #设置里程属性初始值为0 ,无需在init中设置形参 def get_describe_name(self): "返回整洁的汽车描述信息" long_name = str(self.year) + ‘ ‘ + self.make + ‘ ‘ + self.model return long_name.title() def update_odometers(self,miles): "通过方法修改属性odometer_reading的值" self.odometer_reading += miles def reading_odometer(self): "读取汽车的里程" print("This car has " + str(self.odometer_reading) + " miles on it.") class Battery(): "电瓶具有自己的属性和方法,单独做一个类" def __init__(self,battery_size): self.battery_size = battery_size def upgrade_battery(self): if self.battery_size<85: self.battery_size = 85 def describe_battery(self): print("This EletricCar‘s battery is " + str(self.battery_size) + "-kwh") def get_range(self): if self.battery_size <= 70: range = 240 else: range = 280 message = "This car can go approximately " + str(range) message += " miles on a full charge" print(message) class ElectricCar(Car):#电动汽车继承汽车类 "子类ElectricCar继承父类Car" def __init__(self,make,model,year): super().__init__(make,model,year) #初始化父类的属性 self.battery = Battery(70) #实例用作属性 def get_describe_name(self): "假设子类ElectricCar与父类Car的描述不一致,则在子类中重新定义同名方法,Python将不考虑父类中该方法" print("The ElectricCar‘s type is " + str(self.year) + ‘ ‘ + self.make + ‘ ‘ + self.model) my_car = Car(‘audi‘,‘a4‘,2016)#根据类创建实例print(my_car.get_describe_name())my_car.update_odometers(2000)my_car.reading_odometer() my_eletricCar = ElectricCar(‘aima‘,‘e1‘,2017)#根据子类创建实例my_eletricCar.get_describe_name()my_eletricCar.update_odometers(2000)my_eletricCar.reading_odometer()my_eletricCar.battery.describe_battery()my_eletricCar.battery.get_range()my_eletricCar.battery.upgrade_battery() #通过类Battery()里的upgrade_battery将battery更改为85kwhmy_eletricCar.battery.describe_battery() #my_eletricCar.battery传值到类Battery() 调用Battery()的方法describe_batterymy_eletricCar.battery.get_range() 运行结果:2016 Audi A4This car has 2000 miles on it.The ElectricCar‘s type is 2017 aima e1This car has 2000 miles on it.This EletricCar‘s battery is 70-kwhThis car can go approximately 240 miles on a full chargeThis EletricCar‘s battery is 85-kwhThis car can go approximately 280 miles on a full charge
时间: 2024-10-20 08:16:53