类方法生成“TypeError:...获得关键字参数的多个值...” [英] class method generates "TypeError: ... got multiple values for keyword argument ..."

查看:235
本文介绍了类方法生成“TypeError:...获得关键字参数的多个值...”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class foo(object):
def foodo(thing = None,thong ='not innerwear'):
print thing if thing elsenothing
print'a thong is',thong
/ pre>

调用方法会生成 TypeError

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

...
TypeError:有多个值的关键字参数'thing'

发生了什么事?

解决方案

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

  class foo(object):
def foodo(self,thing = None, thong ='not innerwear'):
print thing if thing elsenothing
print'a thong is',thong

它的行为正如预期。



说明:



没有 self 作为第一个参数,当执行 myfoo.foodo(thing =something)时, foodo 方法用参数(myfoo,thing =something)调用。然后将实例 myfoo 分配给 thing (因为 thing 是第一个声明的参数),但是python还试图将something分配给 thing / p>

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

  myfoo .foodo(something)
print
print myfoo

输出如:

 < __ main__.foo object at 0x321c290> 
a thong是东西

< __ main__.foo对象在0x321c290>

你可以看到'thing'已经被分配了对类的实例'myfoo'的引用'foo'。文档的此部分说明了函数参数的工作原理。


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

calling the method generates a TypeError:

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

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

What's going on?

解决方案

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

it behaves as expected.

Explanation:

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

You'll output like:

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

<__main__.foo object at 0x321c290>

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:...获得关键字参数的多个值...”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆