我的代码快完成了,但我还是搞不懂一件事。问题是:Write a class named Car that has the following data attributes:__year_model
__make
__speed
The Car class should have an __init__ method that accepted the car's year model and make as arguments. These values should be assigned to the object's __year_model and __make data attributes. It should also assign 0 to the __speed data attribute. The class should also have the following methods:accelerate: The accelerate method should add 5 to the speed data attribute each time it is called.
brake: the brake method should subtract 5 from the speed data attribute each time it is called.
get_speed: The get_speed method should return the current speed
Next, design a program that creates a Car object and then calls the accelerate method five times. After each call to the accelerate method, get the current speed of the car and display it. Then call the brake method five times and do the same. However, when the car is braked and speed >0 it should display an error message and reset speed back to 0.
最后一行是我有困难的部分。它正确地加5和减5,但当它小于0时不显示错误消息。这是我的类定义代码和测试它的代码。谢谢你的帮助。在class Car:
def __init__(self, year_model, make):
self.__year_model = year_model
self.__make = make
self.__speed = 0
############# year_model################
def setYear_model(self, year_model):
self.__year_model = year_model
def getYear_model(self):
return self.__year_model
############# Make################
def setMake(self, make):
self.__make = make
def getMake(self):
return self.make
############# speed################
def setSpeed(self, speed):
if speed < 0:
print("Speed cannot be negative")
else:
self.__speed = speed
def getSpeed(self):
return self.__speed
def accelerate(self):
self.__speed += 5
return self.__speed
def brake(self):
self.__speed -= 5
return self.__speed
############# str ############
def __str__(self):
return "Make : " + self.__make + ", Model Year :" + \
self.__year_model + ", speed = " + str(self.__speed)
import ag_CarDefinition
def main():
# Create an instance of Car
my_car = ag_CarDefinition.Car("2008", "Honda Accord")
print(my_car)
print("my_car after instantiating:\n", my_car)
my_car.setSpeed(2)
print("my_car after my_car.setSpeed(2):\n", my_car)
# Accelerate 5 times
print ("car is accelerating: ")
for i in range(5):
my_car.accelerate()
print ("Current speed: ", my_car.getSpeed())
print()
# Brake 7 times
print ("car is braking: ")
for i in range(7):
my_car.brake()
print ("Current speed: ", my_car.getSpeed())
print("my_car values at program end:\n", my_car)
main()