在python中传递参数时参数之前做什么**?

In python when passing arguments what does ** before an argument do?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
What does *args and **kwargs mean?

从阅读这个例子和我对python的微薄了解来看,它一定是将数组转换为字典或其他东西的快捷方式。

1
2
3
4
5
class hello:
    def GET(self, name):
        return render.hello(name=name)
        # Another way:
        #return render.hello(**locals())


在python中,f(**d)将字典d中的值作为关键字参数传递给函数f。类似地,f(*a)将数组a中的值作为位置参数传递。

举个例子:

1
2
3
def f(count, msg):
  for i in range(count):
    print msg

使用**d*a调用此函数:

1
2
3
4
5
6
7
>>> d = {'count': 2, 'msg':"abc"}
>>> f(**d)
abc
abc
>>> a = [1,"xyz"]
>>> f(*a)
xyz

**local()传递与调用方的本地命名空间相对应的字典。当传递带有**的函数时,将传递字典,这将允许可变长度参数列表。


从python文档5.3.4:

If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax **identifier is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.

在不同的上下文中,这也用于电源运算符。


它将字典"解包"为参数列表。IE:

1
2
def somefunction(keyword1, anotherkeyword):
   pass

它可以被称为

1
2
3
4
somefunction(keyword1=something, anotherkeyword=something)
or as
di = {'keyword1' : 'something', anotherkeyword : 'something'}
somefunction(**di)