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)
Similar Posts:
- How to Solve Python Error : **kwargs and takes 1 positional argument but 2 were given
- Python: __ new__ Method and the processing of typeerror: object() takes no parameters
- [Solved] Java Call Error: java.lang.IllegalArgumentException: wrong number of arguments
- java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal …
- Fatal error: Call-time pass-by-reference has be…
- The influence of UVM environment on UVM_ config_ Understanding of DB
- Python Typeerror: super() takes at least 1 argument (0 given) error in Python
- Python: How to Calculate the Distance of Latitude and Longitude
- Python TypeError: unbound method a() must be called with A instance as first argument (go…
- How to solve the problem of potentially unsupported type in Python sqllite