# `**` （双星）和`*` （星星）对参数做什么？

## 定义函数

`*args`允许任意数量的可选位置参数（参数），它们将被分配给一个名为`args`的元组。

`**kwargs`允许任意数量的可选关键字参数（参数），这些参数将在一个名为`kwargs`的字典中。

## 扩展，传递任意数量的参数

``````>>> x = xrange(3) # create our *args - an iterable of 3 integers
>>> xrange(*x)    # expand here
xrange(0, 2, 2)
``````

``````>>> foo = 'FOO'
>>> bar = 'BAR'
>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())
'this is foo, FOO and bar, BAR'
``````

## Python 3中的新增内容：使用仅关键字参数定义函数

``````def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):
return arg, kwarg, args, kwarg2, kwargs
``````

``````>>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')
(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})
``````

``````def foo(arg, kwarg=None, *, kwarg2=None, **kwargs):
return arg, kwarg, kwarg2, kwargs
``````

``````>>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')
(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})
``````

``````>>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes from 1 to 2 positional arguments
but 5 positional arguments (and 1 keyword-only argument) were given
``````

``````def bar(*, kwarg=None):
return kwarg
``````

``````>>> bar('kwarg')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 0 positional arguments but 1 was given
``````

``````>>> bar(kwarg='kwarg')
'kwarg'
``````

## Python 2兼容演示

`*args` （通常称为“星形参数”）和`**kwargs` （星号可以用“kwargs”来表示，但用“double-star kwargs”来表示）是使用`*``**`符号的Python常见成语。 这些特定的变量名称不是必需的（例如，您可以使用`*foos``**bars` ），但与惯例背离可能会让您的Python编码人员`*foos`

``````def foo(a, b=10, *args, **kwargs):
'''
this function takes required argument a, not required keyword argument b
and any number of unknown positional arguments and keyword arguments after
'''
print('a is a required argument, and its value is {0}'.format(a))
print('b not required, its default value is 10, actual value: {0}'.format(b))
# we can inspect the unknown arguments we were passed:
#  - args:
print('args is of type {0} and length {1}'.format(type(args), len(args)))
for arg in args:
print('unknown arg: {0}'.format(arg))
#  - kwargs:
print('kwargs is of type {0} and length {1}'.format(type(kwargs),
len(kwargs)))
for kw, arg in kwargs.items():
print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))
# But we don't have to know anything about them
# to pass them to other functions.
print('Args or kwargs can be passed without knowing what they are.')
# max can take two or more positional args: max(a, b, c...)
print('e.g. max(a, b, *args) \n{0}'.format(
max(a, b, *args)))
kweg = 'dict({0})'.format( # named args same as unknown kwargs
', '.join('{k}={v}'.format(k=k, v=v)
for k, v in sorted(kwargs.items())))
print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(
dict(**kwargs), kweg=kweg))
``````

``````foo(a, b=10, *args, **kwargs)
``````

``````a is a required argument, and its value is 1
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 2
unknown arg: 3
unknown arg: 4
kwargs is of type <type 'dict'> and length 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: g, arg: 7
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
4
e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:
{'e': 5, 'g': 7, 'f': 6}
``````

``````def bar(a):
b, c, d, e, f = 2, 3, 4, 5, 6
# dumping every local variable into foo as a keyword argument
# by expanding the locals dict:
foo(**locals())
``````

`bar(100)`打印：

``````a is a required argument, and its value is 100
b not required, its default value is 10, actual value: 2
args is of type <type 'tuple'> and length 0
kwargs is of type <type 'dict'> and length 4
unknown kwarg - kw: c, arg: 3
unknown kwarg - kw: e, arg: 5
unknown kwarg - kw: d, arg: 4
unknown kwarg - kw: f, arg: 6
Args or kwargs can be passed without knowing what they are.
e.g. max(a, b, *args)
100
e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:
{'c': 3, 'e': 5, 'd': 4, 'f': 6}
``````

``````def foo(a, b, c, d=0, e=100):
# imagine this is much more code than a simple function call
preprocess()
differentiating_process_foo(a,b,c,d,e)
# imagine this is much more code than a simple function call
postprocess()

def bar(a, b, c=None, d=0, e=100, f=None):
preprocess()
differentiating_process_bar(a,b,c,d,e,f)
postprocess()

def baz(a, b, c, d, e, f):
... and so on
``````

``````def decorator(function):
'''function to wrap other functions with a pre- and postprocess'''
@functools.wraps(function) # applies module, name, and docstring to wrapper
def wrapper(*args, **kwargs):
# again, imagine this is complicated, but we only write it once!
preprocess()
function(*args, **kwargs)
postprocess()
return wrapper
``````

``````@decorator
def foo(a, b, c, d=0, e=100):
differentiating_process_foo(a,b,c,d,e)

@decorator
def bar(a, b, c=None, d=0, e=100, f=None):
differentiating_process_bar(a,b,c,d,e,f)

@decorator
def baz(a, b, c=None, d=0, e=100, f=None, g=None):
differentiating_process_baz(a,b,c,d,e,f, g)

@decorator
def quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):
differentiating_process_quux(a,b,c,d,e,f,g,h)
``````

``````def foo(param1, *param2):
def bar(param1, **param2):
``````

* args = * aList =列表中的所有元素

** args = ** aDict =字典中的所有项目

`*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
``````

``````first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]
``````

``````def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
pass
``````

``````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 = {'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'
``````

``````>>> (0, *range(1, 4), 5, *range(6, 8))
(0, 1, 2, 3, 5, 6, 7)
>>> [0, *range(1, 4), 5, *range(6, 8)]
[0, 1, 2, 3, 5, 6, 7]
>>> {0, *range(1, 4), 5, *range(6, 8)}
{0, 1, 2, 3, 5, 6, 7}
>>> d = {'one': 1, 'two': 2, 'three': 3}
>>> e = {'six': 6, 'seven': 7}
>>> {'zero': 0, **d, 'five': 5, **e}
{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}
``````

``````>>> range(*[1, 10], *[2])
range(1, 10, 2)
``````

（感谢mgilson为PEP链接。）

``````            In function *construction*      In function *call*
=======================================================================
|  def f(*args):                 |  def f(a, b):
*args     |      for arg in args:          |      return a + b
|          print(arg)            |  args = (1, 2)
|  f(1, 2)                       |  f(*args)
----------|--------------------------------|---------------------------
|  def f(a, b):                  |  def f(a, b):
**kwargs  |      return a + b              |      return a + b
|  def g(**kwargs):              |  kwargs = dict(a=1, b=2)
|      return f(**kwargs)        |  f(**kwargs)
|  g(a=1, b=2)                   |
-----------------------------------------------------------------------
``````

*还可以解压一个发电机

Python3 Document的一个例子

``````x = [1, 2, 3]
y = [4, 5, 6]

unzip_x, unzip_y = zip(*zip(x, y))
``````

unzip_x将会是[1,2,3]，unzip_y将会是[4,5,6]

zip（）接收多个iretable参数，并返回一个生成器。

``````zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
``````

``````class base(object):
def __init__(self, base_param):
self.base_param = base_param

class child1(base): # inherited from base class
def __init__(self, child_param, *args) # *args for non-keyword args
self.child_param = child_param
super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg

class child2(base):
def __init__(self, child_param, **kwargs):
self.child_param = child_param
super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg

c1 = child1(1,0)
c2 = child2(1,base_param=0)
print c1.base_param # 0
print c1.child_param # 1
print c2.base_param # 0
print c2.child_param # 1
``````

``````def __init__(self, *args, **kwargs):
for attribute_name, value in zip(self._expected_attributes, args):
setattr(self, attribute_name, value)
if kwargs.has_key(attribute_name):
kwargs.pop(attribute_name)

for attribute_name in kwargs.viewkeys():
setattr(self, attribute_name, kwargs[attribute_name])
``````

``````class RetailItem(Item):
_expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']

class FoodItem(RetailItem):
_expected_attributes = RetailItem._expected_attributes +  ['expiry_date']
``````

``````food_item = FoodItem(name = 'Jam',
price = 12.0,
category = 'Foods',
country_of_origin = 'US',
expiry_date = datetime.datetime.now())
``````

``````class ElectronicAccessories(RetailItem):
_expected_attributes = RetailItem._expected_attributes +  ['specifications']
# Depend on args and kwargs to populate the data as needed.
def __init__(self, specifications = None, *args, **kwargs):
self.specifications = specifications  # Rest of attributes will make sense to parent class.
super(ElectronicAccessories, self).__init__(*args, **kwargs)
``````

``````usb_key = ElectronicAccessories(name = 'Sandisk',
price = '\$6.00',
category = 'Electronics',
country_of_origin = 'CN',
specifications = '4GB USB 2.0/USB 3.0')
``````