请选择 进入手机版 | 继续访问电脑版

Java321技术网

 找回密码
 立即注册
搜索
热搜: 免费vip视频
科学上网用Google淘宝直通车创意批量采集视频网站通用VIP会员
查看: 1967|回复: 0

TypeError: method() takes 1 positional argument but 2 were given

[复制链接]

39

主题

42

帖子

431

积分

超级版主

Rank: 8Rank: 8

积分
431
发表于 2017-6-16 02:46:30 | 显示全部楼层 |阅读模式
本帖最后由 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
复制代码




回复

使用道具 举报

QQ|Archiver|手机版|小黑屋|Java321技术网 ( 蜀ICP备15030946号-1

GMT+8, 2019-10-16 06:16 , Processed in 0.062971 second(s), 20 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表