当您将关键字参数传递给函数时,它将转换为字典。不是相反。在
args和kwargs的详细说明
*args表示函数/方法可以接受任意数量的位置参数,并将存储在名为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用于自动将所有命名参数存储为字典。在