这里就补充面向对象编程中遗漏的知识点
目录
修改属性的值有三种方法:直接通过实例进行修改;通过方法进行设置;通过方法进行递增(增加的值)
首先我们定义一个车的类型的类,然后再加上车行驶的距离的一个属性赋初值 0
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.orometer_reading = 0 #这个是我们定义的车行驶的距离
def get_description(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name
def read_odometer(self):
print("This car has "+ str(self.orometer_reading) + " miles on it")
my_new_car = Car("aodi", "a6", 2017)
print(my_new_car.get_description())
my_new_car.read_odometer()
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.orometer_reading = 0
def get_description(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name
def read_odometer(self):
print("This car has "+ str(self.orometer_reading) + " miles on it")
my_new_car = Car("aodi", "a6", 2017)
print(my_new_car.get_description())
#直接更改,修改初始化中的属性--
my_new_car.orometer_reading = 14
my_new_car.read_odometer()
我们在原有的程序基础上再 加一个方法,加入判定条件:汽车走过的路程是不能减少的
接着上面的程序
def update_orometer(self,miles):
if miles >= self.orometer_reading:
self.orometer_reading = miles
else:
print("You can'troll back an odometer")
#通过方法来修改
my_new_car.update_orometer(25)
my_new_car.read_odometer()
也就是说,我们需要再定义一个方法,在原有的路程进行增加走过的路程
接上
def increase(self,miles):
self.orometer_reading +=miles
#通过方法对属性的值进行递增
my_used_car = Car("bentian","outback",2006)
print(my_used_car.get_description())
my_used_car.update_orometer(3500)#先赋值,更新现在所走的路程
my_used_car.read_odometer()
my_used_car.increase(100)
my_used_car.read_odometer()