If I have a class...
class MyClass: def method(arg): print(arg)
...which I use to create an object...
my_object = MyClass()
...on which I call method("foo")
like so...
>>> my_object.method("foo") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: method() takes exactly 1 positional argument (2 given)
...why does Python tell me I gave it two arguments, when I only gave one?
In this situation, we either have to update the function's declaration and take a second argument or remove the second argument from the function call.
The Python rule says positional arguments must appear first, followed by the keyword arguments if we are using it together to call the method. The SyntaxError: positional argument follows keyword argument means we have failed to follow the rules of Python while writing a code.
A positional argument in Python is an argument whose position matters in a function call. You have likely used positional arguments without noticing. For instance: def info(name, age): print(f"Hi, my name is {name}.
In Python, this:
my_object.method("foo")
...is syntactic sugar, which the interpreter translates behind the scenes into:
MyClass.method(my_object, "foo")
...which, as you can see, does indeed have two arguments - it's just that the first one is implicit, from the point of view of the caller.
This is because most methods do some work with the object they're called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self
inside the method definition:
class MyNewClass: def method(self, arg): print(self) print(arg)
If you call method("foo")
on an instance of MyNewClass
, it works as expected:
>>> my_new_object = MyNewClass() >>> my_new_object.method("foo") <__main__.MyNewClass object at 0x29045d0> foo
Occasionally (but not often), you really don't care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod()
function to say so:
class MyOtherClass: @staticmethod def method(arg): print(arg)
...in which case you don't need to add a self
argument to the method definition, and it still works:
>>> my_other_object = MyOtherClass() >>> my_other_object.method("foo") foo
In simple words.
In Python you should add self
argument as the first argument to all defined methods in classes:
class MyClass: def method(self, arg): print(arg)
Then you can use your method according to your intuition:
>>> my_object = MyClass() >>> my_object.method("foo") foo
This should solve your problem :)
For a better understanding, you can also read the answers to this question: What is the purpose of self?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With