码迷,mamicode.com
首页 > 其他好文 > 详细

类的操作-汽车类

时间:2017-09-22 15:30:07      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:属性   实例   range   let   zha   reading   sage   init   子类   

#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更改为85kwh
my_eletricCar.battery.describe_battery() #my_eletricCar.battery传值到类Battery() 调用Battery()的方法describe_battery
my_eletricCar.battery.get_range()

运行结果:
2016 Audi A4
This car has 2000 miles on it.
The ElectricCar‘s type is 2017 aima e1
This car has 2000 miles on it.
This EletricCar‘s battery is 70-kwh
This car can go approximately 240 miles on a full charge
This EletricCar‘s battery is 85-kwh
This car can go approximately 280 miles on a full charge

类的操作-汽车类

标签:属性   实例   range   let   zha   reading   sage   init   子类   

原文地址:http://www.cnblogs.com/ekura/p/7574694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!