欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

编写类-汽车类

程序员文章站 2022-07-09 21:32:56
# Author:Eric Zhao# -*- coding:utf-8 -*-'一个可用用于表示汽车的类'class Car(): def __init__(self,make,model,year): '初始化描述汽车的属性' self.make = make self.model = mode ......
# author:eric zhao
# -*- coding:utf-8 -*-
'一个可用用于表示汽车的类'
class car():
def __init__(self,make,model,year):
'初始化描述汽车的属性'
self.make = make
self.model = model
self.year = year
self.odometer_reading = 10

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

my_car = car('gm','cadillac',2019)
print(my_car.get_descriptive_name())
my_car.read_odometer()
my_car.update_odometer(15)
my_car.read_odometer()