我必须打电话给"加速"方法5次,并在每次迭代后显示它的输出。必须使用" brake"方法。我写了所有这些,但我甚至不知道在哪里开始调用main函数中的方法来实现我想要的目标。任何帮助是极大的赞赏!!我在Python 3.3中
class Car:
def __init__(self):
self.__year_model = 0
self.__make = ''
self.__speed = 0
def set_year_model(self, year):
self.__year_model = year
def set_make(self, make):
self.__make = make
def set_speed(self, speed):
self.__speed = speed
def accelerate(self):
return self.__speed + 5
def brake(self):
return self.__speed - 5
def get_year_model(self):
return self.__year_model
def get_make(self):
return self.__make
def get_speed(self):
return self.__speed
def main():
mycar = Car()
year = input('Enter the year of the vehicle: ')
make = input('Enter the make of the vehicle: ')
speed = input("Enter the vehicle's current speed: ")
mycar.set_year_model(year)
mycar.set_make(make)
mycar.set_speed(speed)
accel = mycar.accelerate()
brake = mycar.brake()
main()
答案 0 :(得分:1)
这可以通过简单的循环结构来解决。在您的main方法中,尝试:
for item in range(0,5):
accel = mycar.accelerate()
print(accel)
编辑:请注意,这可能不是最好的方法,但首先想到的方式。关于int / str转换,您可能只想转换。我通常使用Python 2.7.x并且不记得是否需要为Python 3.0的打印函数强制转换为字符串。
答案 1 :(得分:1)
您的accelerate
代码错误:永远不会存储更改的速度。它应该是
def accelerate(self):
self.__speed += 5
,同样适用于brake
。
编辑: getter和setter方法并不是真正的惯用Python。你可能想要
class Car:
def __init__(self, year, make, speed=0):
self.year = year
self.make = make
self.speed = speed
def accelerate(self, amount=5):
self.speed += amount
def brake(self, amount=5):
self.speed -= amount
def main():
year = input('Enter the year of the vehicle: ')
make = input('Enter the make of the vehicle: ')
speed = input("Enter the vehicle's current speed: ")
mycar = Car(year, make, int(speed))
print("Accelerating:")
for _ in range(5):
mycar.accelerate()
print(mycar.speed)
print("Braking:")
for _ in range(5):
mycar.brake()
print(mycar.speed)
if __name__=="__main__":
main()
给出了
Enter the year of the vehicle: 1990
Enter the make of the vehicle: Corolla
Enter the vehicle's current speed: 20
Accelerating:
25
30
35
40
45
Braking:
40
35
30
25
20