我写了一个名为car的类,其中包含属性model,year和speed。它还有3种方法,加速,制动,honk_horn。每次加速调用时我都会尝试添加5,但我无法使其工作。我在这里做错了什么?
class Car:
"""Defines the Car class.
Data attributes: model of type str
year of type int
speed of type float
"""
def __init__(self, model, year, speed=0):
"""Creates new Car object with specified model, year, and speed"""
self.model = model
self.year = year
self.speed = speed
def accelerate(self):
self.speed + 5 #everytime it is called
def brake(self):
if self.speed != 0: #If speed already zero don't minus 5
self.speed - 5
else:
self.speed
def honk_horn(self):
print("{} goes 'beep beep'".format(self.model))
我在使用下面的测试进行测试时应该得到35分,但我只得到30分:
my_car = Car("Zastava", 2001, 30)
my_car.accelerate()
my_car.accelerate()
my_car.brake()
print(my_car.speed)
答案 0 :(得分:5)
您没有为self.speed
分配值。您只需在不使用结果的情况下执行数学运算。
以下更改声明:
self.speed + 5 #everytime it is called
到此:
self.speed = self.speed + 5 #everytime it is called
或者这个:
self.speed += 5 #everytime it is called
答案 1 :(得分:1)
self.speed + 5 #everytime it is called
应该是
self.speed += 5 #everytime it is called
我添加了一个+ =而不是+
此外,您的brake
功能以类似方式出错
答案 2 :(得分:0)
变化{
"id":1048,
"order_status":"cancel",
"items":[
{
"id":5000,
"name":"baseball hat"
}
]
}
到self.speed + 5
变化self.speed = self.speed + 5
到self.speed - 5
应该工作