Monday, December 11, 2017

[Python3][Resolved] start_engine() takes 0 positional arguments but 1 was given

Error message

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-8f585077ddb5> in <module>()
     23 newCar = Car()
     24 print(newCar.color)
---> 25 print(newCar.start_engine())
     26 print(newCar.drive())
     27 print(newCar.stop_engine())

TypeError: start_engine() takes 0 positional arguments but 1 was given

Source code

class Car:
    color = "Blue"

    def start_engine():
        print("Starting the engine!")
    def drive():
        print("Driving the car!")
    def stop_engine():
        print("Turning off the car!")

newCar = Car()
print(newCar.color)
print(newCar.start_engine())
print(newCar.drive())
print(newCar.stop_engine())

Solution

Since the method in class is a class method but not a function, we need a 'self' parameter :
class Car:
    color = "Blue"

    def start_engine(self):
        print("Starting the engine!")
    def drive(self):
        print("Driving the car!")
    def stop_engine(self):
        print("Turning off the car!")

newCar = Car()
print(newCar.color)
print(newCar.start_engine())
print(newCar.drive())
print(newCar.stop_engine())

Reference

https://www.tutorialspoint.com/python/python_classes_objects.htm
https://stackoverflow.com/questions/18884782/typeerror-worker-takes-0-positional-arguments-but-1-was-given

No comments :

Post a Comment