Home >Backend Development >Python Tutorial >Why Does 'TypeError: method() takes 1 positional argument but 2 were given' Occur Even with One Explicit Argument?
"TypeError: method() takes 1 positional argument but 2 were given" with Only One Argument Passed
When encountering the error "TypeError: method() takes 1 positional argument but 2 were given" despite passing only one argument, it's important to understand Python's method calling convention.
In Python, method calls are syntactic sugar for a more verbose syntax. When calling a method on an object, the language translates the call into a more explicit form, where the object becomes the first argument to the method.
For example, the following call:
my_object.method("foo")
is translated behind the scenes into:
MyClass.method(my_object, "foo")
Here, the first argument (my_object) is called the self parameter within the method definition. This parameter represents the object on which the method is being called.
In most cases, methods require access to the object they're called on. But occasionally, you may want a method that doesn't depend on the object it's bound to. In such cases, you can use Python's staticmethod() function to decorate the method:
class MyOtherClass: @staticmethod def method(arg): print(arg)
Decorating a method with staticmethod() eliminates the need for a self parameter, allowing you to call the method directly without referencing the object:
my_other_object.method("foo")
This clarifies why the error you encountered states that two arguments were provided. Python is interpreting the object on which you're calling the method (e.g., my_object in the original example) as an implicit first argument, resulting in a total of two arguments being passed.
The above is the detailed content of Why Does 'TypeError: method() takes 1 positional argument but 2 were given' Occur Even with One Explicit Argument?. For more information, please follow other related articles on the PHP Chinese website!