python - TypeError: method() takes 1 positional argument but 2 were given -
if have class ...
class myclass: def method(arg): print(arg) ... use create object ...
my_object = myclass() ... on call method("foo") ...
>>> my_object.method("foo") traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: method() takes 1 positional argument (2 given) ... why python tell me gave 2 arguments, when gave one?
in python, this:
my_object.method("foo") ... syntactic sugar, interpreter translates behind scenes into:
myclass.method(my_object, "foo") ... which, can see, indeed have 2 arguments - it's first 1 implicit, point of view of caller.
this because methods work object they're called on, there needs way object referred inside method. convention, first argument called self inside method definition:
class mynewclass: def method(self, arg): print(self) print(arg) if call method("foo") on instance of mynewclass, works expected:
>>> my_new_object = mynewclass() >>> my_new_object.method("foo") <__main__.mynewclass object @ 0x29045d0> foo occasionally (but not often), don't care object method bound to, , in circumstance, can decorate method builtin staticmethod() function so:
class myotherclass: @staticmethod def method(arg): print(arg) ... in case don't need add self argument method definition, , still works:
>>> my_other_object = myotherclass() >>> my_other_object.method("foo") foo
Comments
Post a Comment