Python 方法采用一个位置参数,但给出了两个

Python method takes one positional argument but two were given

我遇到了一个我不太明白的错误。如果我有以下代码段:

class Test(object):
  def __init__(self):
    self.data = {}

  def update_data(self, **update):
    self.data = update

t = Test()

t.update_data(test='data') #  Works
t.update_data({'test':'data'}) #  TypeError: update_data() takes 1 positional argument but 2 were given

所以据我了解,**update 语法是字典破坏语法,当您将字典传递给函数时,它会转换为关键字参数。

我哪里理解错了?

当您将关键字参数传递给函数时,它会转换为字典。反之则不然。

args和kwargs的详细解释

*args 表示 function/method 可以接受任意数量的位置参数,并将存储在名为 args 的列表中。

**kwargs 表示它可以接受任意数量的命名参数,并将存储在名为 kwargs 的字典中 还不清楚吗?让我举个例子(虽然很简单和幼稚)-

# Suppose you want to write a function that can find the 
# sum of all the numbers passed to it.

def sum(a, b):
    return a + b

>>> sum(2, 3) # => 5

# Now this function can only find sum of two numbers, what 
# if we have 3, 4 or more numbers, how would be go solving that.
# Easy let's take an array/list as an argument -

def sum(numbers):
    total = 0

    for number in numbers:
        total += number

    return total

# But now we'd have to call it like -
>>> sum([2, 3]) # => 5
>>> sum(2, 3) # => throws an error.

# That might be ok for some other programming languages, but not 
# for Python. So python allows you to pass any number of 
# arguments, and it would automatically store them into list 
# called args (as a conventions, but it can be called 
# anything else say 'numbers')

def sum(*numbers):
    total = 0

    for number in numbers:
        total += number

    return total

>>> sum(2, 3, 4) # => 9

# Viola! 

类似的 kwargs 用于自动将所有命名参数存储为字典。

如果您只是传入字典,它将被视为任何其他变量。在您的情况下,您将其作为位置参数传入,因此它将被视为位置参数。但是,该方法不接受任何位置参数(self 除外,但那是另一回事)因此它会引发错误。

如果您想将字典 contents 作为关键字参数传递,您需要将其解压(** 在字典前面):

t.update_data(**{'test':'data'})

如果你想将字典作为字典传递,你也可以将它作为关键字参数传递(这样就不需要解包了!):

t.update_data(funkw={'test':'data'})