. Advertisement .
..3..
. Advertisement .
..4..
I still get the error ”takes 2 positional arguments but 3 were given” when running my program:
class MyClass:
def method(arg):
print(arg)
I use it to create an object…
my_object = MyClass()
When I call method("foo")
, I receive the error message:
>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)
I don’t know how to resolve the issue. Can someone help me?
The cause: The reason is that all instance methods expect a first arg which by custom we call
self
. The correct declaration for a method isdef method(self, arg):
, not thedef method(arg):
his issue occurs when the method dispatch tries to callmethod(arg):
and match up two parametersself, arg
against it.Solution: You need to add
self
argument as the first argument to all defined methods in classes:After that, you can use your strategy based on your intuition: