使用方法创建类

时间:2017-10-09 10:44:27

标签: python-3.x class python-3.5

我写了一个名为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)

3 个答案:

答案 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 + 5self.speed - 5 应该工作