Home > Backend Development > Python Tutorial > Why Does 'TypeError: method() takes 1 positional argument but 2 were given' Occur Even with One Explicit Argument?

Why Does 'TypeError: method() takes 1 positional argument but 2 were given' Occur Even with One Explicit Argument?

Mary-Kate Olsen
Release: 2024-12-30 13:25:10
Original
584 people have browsed it

Why Does

"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")
Copy after login

is translated behind the scenes into:

MyClass.method(my_object, "foo")
Copy after login

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)
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template