将实例用作属性
1 # # coding=GBK 2 class Car(): 3 """一次模拟汽车的简单尝试""" 4 5 def __init__ (self , make , model , year): 6 """初始化描述汽车的属性""" 7 self.make = make 8 self.model = model 9 self.year = year 10 self.odometer_reading = 0 11 12 def get_descriptive_name(self): 13 """返回整洁的描述性信息""" 14 long_name = str(self.year) + ' ' + self.make + ' ' +self.model 15 return long_name.title() 16 17 def read_odometer(self): 18 """打印一条指出汽车里程数的消息""" 19 print("This car has " + str(self.odometer_reading) + " miles on it.") 20 21 def update_odometer(self , mileage): 22 """ 23 将里程表读数设置为指定的值 24 禁止将里程表读数往回调 25 """ 26 if mileage >= self.odometer_reading: 27 self.odometer_reading = mileage 28 else: 29 print("You can't roll back an ododmeter!") 30 31 32 def increment_odometer(self , miles): 33 """将里程表读数增加指定的量""" 34 self.odometer_reading += miles 35 36 class Battery(): 37 """一次模拟电动汽车电瓶的简单尝试""" 38 39 def __init__ (self , battery_size = 70): 40 """初始化电瓶的属性""" 41 self.battery_size = battery_size 42 43 def describe_battery(self): 44 """打印一条描述电瓶容量的消息""" 45 print("This car has a " + str(self.battery_size) + "-kwh battery.") 46 47 def get_range(self): 48 """打印一条消息,指出电瓶的续航里程""" 49 if self.battery_size ==70: 50 range = 240 51 elif self.battery_size == 85: 52 range = 270 53 54 message = "This car can go approximately " + str(range) 55 message += "miles on a full charge." 56 print(message) 57 58 class ElectricCar(Car): 59 """电动汽车的独特之处""" 60 61 def __init__ (self , make , model , year): 62 """ 63 电动汽车的独特之处 64 初始化父亲的属性,再初始化电动汽车特有的属性 65 """ 66 super(). __init__ (make , model , year) 67 self.battery = Battery() 68 69 def describe_battery(self): 70 """打印一条描述电瓶容量的消息""" 71 print("This car has a " + str(self.battery_size) + "-kwh battery.") 72 73 my_tesla = ElectricCar('tesla' , 'model s' , 2016) 74 print(my_tesla.get_descriptive_name()) 75 my_tesla.battery.describe_battery() 76 my_tesla.battery.get_range()
将实例用作属性:把实例当做一个大的包含多个属性的集合标题来进行看待,然后应用实例也就等于使用多个属性的合集。从而使属性分类清晰,引用便捷,把实例引用到另一个大的实例中,从而在使用每一个大的实例时都可以自动创建小的实例。