我寫了一個名爲car的類,其屬性模型,年份和速度。它也有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)
你必須做'self.speed = self.speed + 5'或'self.speed + = 5' – MushroomMauLa