问题描述
如果我这样定义一个带有关键字参数的类方法:
If I define a class method with a keyword argument thus:
class foo(object):
def foodo(thing=None, thong='not underwear'):
print thing if thing else "nothing"
print 'a thong is',thong
调用该方法会生成一个TypeError
:
calling the method generates a TypeError
:
myfoo = foo()
myfoo.foodo(thing="something")
...
TypeError: foodo() got multiple values for keyword argument 'thing'
怎么回事?
推荐答案
问题在于python中传递给类方法的第一个参数始终是调用该方法的类实例的副本,通常标记为自我
.如果类是这样声明的:
The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled self
. If the class is declared thus:
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")
被执行时,foodo
方法被调用带参数 (myfoo, thing="something")
.然后将实例 myfoo
分配给 thing
(因为 thing
是第一个声明的参数),但是 python 也尝试分配 "something"
到 thing
,因此异常.
Without self
as the first parameter, when myfoo.foodo(thing="something")
is executed, the foodo
method is called with arguments (myfoo, thing="something")
. The instance myfoo
is then assigned to thing
(since thing
is the first declared parameter), but python also attempts to assign "something"
to thing
, hence the Exception.
为了演示,请尝试使用原始代码运行:
To demonstrate, try running this with the original code:
myfoo.foodo("something")
print
print myfoo
你会输出如下:
<__main__.foo object at 0x321c290>
a thong is something
<__main__.foo object at 0x321c290>
您可以看到thing"已分配给foo"类的实例myfoo"的引用.文档的这一部分解释了函数参数的工作原理.
You can see that 'thing' has been assigned a reference to the instance 'myfoo' of the class 'foo'. This section of the docs explains how function arguments work a bit more.
这篇关于类方法生成“TypeError:...获得多个关键字参数值...";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!