4

我试图了解 python 中函数定义中 *args 和 **args 之间的区别。在下面的示例中,*args 用于打包成一个元组并计算总和。

>>> def add(*l):
... sum = 0
... for i in l:
... sum+=i
... return sum ...
>>> add(1,2,3)
6
>>> l = [1,2,3]
>>>add(*l)
6

对于 ** 参数,

>>> def f(**args):
...     print(args)
... 
>>> f()
{}
>>> f(de="Germnan",en="English",fr="French")
{'fr': 'French', 'de': 'Germnan', 'en': 'English'}
>>> 

我看到它接受参数并变成字典。但我不理解使用 ** args 时可能有用的实用程序或其他东西。事实上,我不知道 *args 和 **args 叫什么(vararg 和?)

谢谢

4

1 回答 1

10

When you use two asterisks you usually call them **kwargs for keyword arguments. They are extremely helpful for passing parameters from function to function in a large program.

A nice thing about keyword arguments is that it is really easy to modify your code. Let's say that in the below example you also decided that parameter cube is also relevant. The only thing you would need to do is add one if statement in my_func_2, and you would not need to add a parameter to every function that is calling my_func_2, (as long as that functions has **kwargs).

Here is a simple rather silly example, but I hope it helps:

def my_func_1(x, **kwargs):
    if kwargs.get('plus_3'):
        return my_func_2(x, **kwargs) + 3
    return my_func_2(x, **kwargs)

def my_func_2(x, **kwargs):
    #Imagine that the function did more work
    if kwargs.get('square'):
        return x ** 2
    # If you decided to add cube as a parameter 
    # you only need to change the code here:
    if kwargs.get('cube'):
        return x ** 3
    return x

Demo:

>>> my_func_1(5)
5
>>> my_func_1(5, square=True)
25
>>> my_func_1(5, plus_3=True, square=True)
28
>>> my_func_1(5, cube=True)
125
于 2013-09-12T00:55:40.307 回答