类方法生成“TypeError:。。。为关键字参数获取多个值…“

2024-04-16 10:53:34 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我使用关键字参数定义类方法,则:

class foo(object):
  def foodo(thing=None, thong='not underwear'):
    print thing if thing else "nothing" 
    print 'a thong is',thong

调用该方法将生成一个TypeError

myfoo = foo()
myfoo.foodo(thing="something")

...
TypeError: foodo() got multiple values for keyword argument 'thing'

怎么了?


Tags: 方法none参数定义objectfoodef关键字
3条回答

这可能是显而易见的,但它可能会帮助一个从未见过它的人。如果错误地按位置和名称显式地指定参数,则常规函数也会发生这种情况。

>>> def foodo(thing=None, thong='not underwear'):
...     print thing if thing else "nothing"
...     print 'a thong is',thong
...
>>> foodo('something', thing='everything')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foodo() got multiple values for keyword argument 'thing'

问题是,在python中传递给类方法的第一个参数始终是调用该方法的类实例的副本,通常标记为self。如果类是这样声明的:

class foo(object):
  def foodo(self, thing=None, thong='not underwear'):
    print thing if thing else "nothing" 
    print 'a thong is',thong

它的行为和预期的一样。

说明:

在不使用self作为第一个参数的情况下,当执行myfoo.foodo(thing="something")时,使用参数(myfoo, thing="something")调用foodo方法。实例myfoo随后被分配给thing(因为thing是第一个声明的参数),但是python还试图将"something"分配给thing,因此出现异常。

要演示,请尝试使用原始代码运行此命令:

myfoo.foodo("something")
print
print myfoo

输出如下:

<__main__.foo object at 0x321c290>
a thong is something

<__main__.foo object at 0x321c290>

您可以看到“thing”被分配了对类“foo”的实例“myfoo”的引用。^文档中的{a1}进一步解释了函数参数是如何工作的。

谢谢你的指导性文章。我只想提醒一下,如果您得到的是“TypeError:foodo()为关键字参数“thing”得到了多个值,也可能是您在调用函数时错误地将“self”作为参数传递(可能是因为您从类声明中复制了行-这是一个很常见的错误,当您很匆忙的时候)。

相关问题 更多 >