Java321技术网

标题: TypeError: method() takes 1 positional argument but 2 were given [打印本页]

作者: greenss    时间: 2017-6-16 02:46
标题: TypeError: method() takes 1 positional argument but 2 were given
本帖最后由 greenss 于 2017-6-16 02:50 编辑

If I have a class ...
  1. class MyClass:

  2.     def method(arg):
  3.         print(arg)
复制代码
... which I use to create an object ...
  1. my_object = MyClass()
复制代码
... on which I call method("foo") like so ...

  1. >>> my_object.method("foo")
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. 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 Python, this:
  1. my_object.method("foo")
复制代码
... is syntactic sugar, which the interpreter translates behind the scenes into:

  1. 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:
  1. class MyNewClass:

  2.     def method(self, arg):
  3.         print(self)
  4.         print(arg)
复制代码
If you call method("foo") on an instance of MyNewClass, it works as expected:
  1. >>> my_new_object = MyNewClass()
  2. >>> my_new_object.method("foo")
  3. <__main__.MyNewClass object at 0x29045d0>
  4. 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:
  1. class MyOtherClass:

  2.     @staticmethod
  3.     def method(arg):
  4.         print(arg)
复制代码
... in which case you don't need to add a self argument to the method definition, and it still works:
  1. >>> my_other_object = MyOtherClass()
  2. >>> my_other_object.method("foo")
  3. foo
复制代码









欢迎光临 Java321技术网 (https://java321.com/) Powered by Discuz! X3.3