#直接修改属性的值# -*- coding:utf-8 -*- class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 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.") myNewCar = Car(‘audi‘,‘a4‘,2016) print(myNewCar.get_descriptive_name()) myNewCar.odometer_reading = 23 myNewCar.read_odometer()
#通过方法修改属性的值# -*- coding:utf-8 -*- class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 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): self.odometer_reading = mileage myNewCar = Car(‘audi‘,‘a4‘,2016) print(myNewCar.get_descriptive_name()) myNewCar.update_odometer(24) myNewCar.read_odometer()
#通过方法对属性的值进行递增 # -*- coding:utf-8 -*- class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 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 myNewCar = Car(‘audi‘,‘a4‘,2016) print(myNewCar.get_descriptive_name()) myNewCar.update_odometer(23500) myNewCar.read_odometer() myNewCar.increment_odometer(8) myNewCar.read_odometer()
原文地址:https://www.cnblogs.com/leisurelyRD/p/12239419.html
时间: 2024-10-08 14:09:12