1.Car类
编写一个表示汽车的类,它存储了有关汽车的信息
class Car():
#一次模拟汽车的简单尝试
def __init__(self,make,model,year): #1
#初始化汽车的属性
self.make=make
self.model=model
self.year=year
def get_descriptive_name(self): #2
#获得描述性的信息
long_name=str(self.year)+''+self.make+''+self.model
return long_name.title()
my_new_car=Car("audi","a4",2016) #3
print(my_new_car.get_descriptive_name())
1.我们定义了方法_init_()与之前dog类中的一样,这个方法的第一个形参为self;我们还在这个方法中包含了另外三个形参:make、model、year、方法_init_()接受这些形参的值、创建新的Car实例时,我们要指定制造商、型号、年份
2.我们定义了一个名为get_descriptive_name()的方法,它使用属性year,make和model创建一个对汽车进行描述的字符串,让我们无需分别打印每个属性的值
下面给它添加一个时间变化的属性,它存储汽车的总里程
2.给属性指定默认值
类中的每个属性都必须有初始值,哪怕这个值是0或者是空字符串。
下面来添加一个名为odometer_reading的属性它的初始值总为0