1. 程式人生 > >類的操作-汽車類

類的操作-汽車類

pro ima utf sel icc clas ppr 方法 bat

#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

類的操作-汽車類