我正在尝试为类编写代码,并且在类中遇到了巨大的麻烦。问题是我们用一个类Car
编写一个脚本,将speed
方法设置为'0',并在一系列十次迭代中显示速度(调用acceleration
每次brake
五次)。
我得到的错误是:
Traceback (most recent call last): File "C:/Users/Brown Bear/Documents/Wake Tech/CIS115/Python Documents/Lab14P1.py", line 36, in <module> main() File "C:/Users/Brown Bear/Documents/Wake Tech/CIS115/Python Documents/Lab14P1.py", line 27, in main my_speed = Car() TypeError: __init__() missing 3 required positional arguments: 'make', 'model', and 'speed'
这是输出应该是什么的例子:
Enter model of your car: Prius
Enter make of your car: Toyota
Current speed: 5
Current speed: 10
Current speed: 15
Current speed: 20
Current speed: 25
Current speed: 20
Current speed: 15
Current speed: 10
Current speed: 5
Current speed: 0
这是我的代码:
class Car:
def __init__(self, make, model, speed):
self.make = make
self.model = model
self.speed = speed
def accelerate(self):
self.speed += 5
def brake(self):
self.speed -= 5
def get_make(self):
return self.make
def get_model(self):
return self.model
def get_speed(self):
return self.speed
def main():
manuf = input('Enter the car make: ')
mod = input('Enter the car model: ')
my_speed = Car()
for num in range(5):
my_speed.accelerate()
print('Current speed: ', my_speed.get_speed())
for num in range(5):
my_speed.brake()
print('Current speed: ', my_speed.get_speed())
main()
我在这个特定的问题上度过了一段荒谬的时间,尝试了各种各样的方法,我也研究了之前在这里提出的类似问题,但都有点过于复杂,我只需要一个简单的解决方案。任何和所有帮助表示赞赏。谢谢!
答案 0 :(得分:6)
当您创建类的实例时,您没有传递任何参数:
my_speed = Car()
但是你的定义说有3个必需的参数:
def __init__(self, make, model, speed):
所以你需要创建一个Car实例并传递3个参数:make,model和speed。
my_speed = Car(manuf, mod, some_Speed_val)