Tag Archives: -TypeErrortakes 2 positional arguments but 3 were given

Python Error-TypeError:takes 2 positional arguments but 3 were given

Error:

Today, when I write a simple Python class definition code, I encountered the problem of reporting an error: typeerror: drive() takes 2 positional arguments but 3 were given

The code is as follows

class Car:
    speed = 0
    def drive(self,distance):
        time = distance/self.speed
        print(time)

bike = Car()
bike.speed=60
bike.drive(60,80)

After investigation, it was found that it was the self parameter in the def drive (self, distance) method in the class definition

Now let’s take a brief look at the basic information of self in Python

self , which means that the created class instance itself and the method itself can bind various attributes to self, because self points to the created instance itself. When creating an instance, you can’t pass in empty parameters. You must pass in parameters that match the method, but you don’t need to pass in self. The Python interpreter will pass in instance variables by itself

so there are two solutions

method 1: transfer only one parameter. If you want to transfer two parameters, look at method 2

class Car:
    speed = 0
    def drive(self,distance):
        time = distance/self.speed
        print(time)

bike = Car()
bike.speed=60
bike.drive(80)

Method 2:

class Car:
    speed = 0
    def drive(self,distance,speed):
        time = distance/speed
        print(time)
bike = Car()
bike.drive(80,50)