2017-10-09 66 views
0

我寫了一個名爲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) 
+1

你必須做'self.speed = self.speed + 5'或'self.speed + = 5' – MushroomMauLa

回答

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
 self.speed + 5 #everytime it is called 

應該

 self.speed += 5 #everytime it is called 

當我加入的只是+

另外一個+ =而是你brake功能失常以類似的方式

0

變化self.speed + 5self.speed = self.speed + 5 變化self.speed - 5self.speed = self.speed - 5 應該工作

相關問題