**(双星/星号)和*(星号/星号)对参数做什么?
在下面的方法定义中, *和**对param2做了什么? 
def foo(param1, *param2):
def bar(param1, **param2):
  *args和**kwargs是一个常见的习惯用法,它允许任意数量的函数参数,如本节更多关于定义Python文档中的函数所述。 
  *args会给你所有的函数参数作为元组: 
In [1]: def foo(*args):
   ...:     for a in args:
   ...:         print a
   ...:         
   ...:         
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
  **kwargs会给你所有的关键字参数,除了那些对应于形式参数的字典。 
In [5]: def bar(**kwargs):
   ...:     for a in kwargs:
   ...:         print a, kwargs[a]
   ...:         
   ...:         
In [6]: bar(name='one', age=27)
age 27
name one
这两种习语都可以和普通的参数混合使用,以允许一组固定参数和一些可变参数:
def foo(kind, *args, **kwargs):
   pass
  *l成语的另一个用法是在调用函数时解开参数列表 。 
In [9]: def foo(bar, lee):
   ...:     print bar, lee
   ...:     
   ...:     
In [10]: l = [1,2]
In [11]: foo(*l)
1 2
  在Python 3中,可以在赋值左侧使用*l (Extended Iterable Unpacking),尽管它在此上下文中提供了一个列表而不是元组: 
first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
另外Python 3增加了新的语义(参考PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
    pass
  这样的函数只接受3个位置参数, *之后的所有内容只能作为关键字参数传递。 
  同样值得注意的是,在调用函数时也可以使用*和** 。  这是一个快捷方式,允许您直接使用列表/元组或字典将多个参数传递给函数。  例如,如果你有以下功能: 
def foo(x,y,z):
    print("x=" + str(x))
    print("y=" + str(y))
    print("z=" + str(z))
你可以做这样的事情:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
  注意: mydict的键必须与函数foo的参数完全相同。  否则它会抛出一个TypeError : 
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
  单*意味着可以有任何数量的额外位置参数。  foo()可以被调用等foo(1,2,3,4,5)  在foo()中,param2是包含2-5的序列。 
  双**表示可以有任意数量的额外命名参数。  bar()可以像bar(1, a=2, b=3)一样被调用bar(1, a=2, b=3) 。  在bar()的主体中,param2是一个包含{'a':2,'b':3}的字典, 
使用以下代码:
def foo(param1, *param2):
    print param1
    print param2
def bar(param1, **param2):
    print param1
    print param2
foo(1,2,3,4,5)
bar(1,a=2,b=3)
输出是
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
                        链接地址: http://www.djcxy.com/p/163.html
                        上一篇: What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
下一篇: How are generators and coroutines implemented in CPython?
