TypeError: method() takes 3 arguments 4 were given
Posted July 29, 2022 by Rohith ‐ 1 min read
If you are beginner in python programming, it might be frustrating to see this type of error - TypeError: instance_method() takes 3 positional arguments but 4 were given.
You may wonder, you have given the right number of parameters as in the error, but how could it count one more.
TL;DR
Python instance methods take first parameter as self
(also known as this
in other languages like java). So, in the error, if the required parameters are 3, first one will be self
and others will be positional parameters that you need to pass.
So, if the error says takes n positional arguments but n+1 were given
, method takes one self
, and n-1
positional arguments. Pass n-1
positional arguments
Example
This can be demonstrated with an example
class MyClass:
def instance_method(self, p1, p2):
print(f'parameters are: {p1}, {p2}')
def main():
my_object = MyClass()
my_object.instance_method('one', 'two', 'three')
main()
Output:
Traceback (most recent call last):
...
...
my_object.instance_method('one', 'two', 'three')
TypeError: instance_method() takes 3 positional arguments but 4 were given
Here, my_object.instance_method('one', 'two', 'three')
passed with 3 arguments as in the error and the error says, instance_method() takes 3 positional arguments but 4 were given
.
But as we see, instance method takes only 2 parameters excluding self. Python internally passes self
at runtime.
Here we just need to pass only two parameters while calling object method.