**(双星/星号)和*(星号/星号)为参数做了什么?

在下面的方法定义中, ***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会给你所有的关键字参数,除了那些对应于forms参数的字典。

 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个位置参数, *之后的所有内容只能作为关键字parameter passing。

同样值得注意的是,在调用函数时也可以使用*** 。 这是一个快捷方式,允许您直接使用列表/元组或字典将多个parameter passing给函数。 例如,如果你有以下function:

 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

单*意味着可以有任何数量的额外的位置参数。 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} 

** (双星)和* (星星)对参数做什么?

它们允许函数被定义为接受用户传递任意数量的参数,位置( * )和关键字( ** )。

定义函数

*args允许任意数量的可选位置参数(参数),这些参数将被分配给一个名为args的元组。

**kwargs允许任何数量的可选的关键字参数(参数),这将是一个名为kwargs的字典。

您可以(也应该)select任何适当的名称,但是如果意图是使参数具有非特定的语义,则argskwargs是标准名称。

扩展,传递任意数量的参数

您也可以使用*args**kwargs分别从列表(或任何迭代)和string(或任何映射)传入参数。

接收参数的函数不必知道它们正在扩展。

例如,Python 2的xrange没有明确地期望*args ,但是因为它需要3个整数作为参数:

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

作为另一个例子,我们可以在str.format使用dict扩展:

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

Python 3新增内容:使用关键字参数定义函数

你可以在*args之后只有关键字 *args – 例如,在这里, kwarg2必须作为关键字参数给出 – 不是位置:

 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 

在这里, kwarg2再次必须是一个明确命名的关键字参数:

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

而且我们不能再接受无限的位置参数,因为我们没有*args*

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

再次,更简单地说,在这里,我们要求kwarg的名称,而不是位置:

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

在这个例子中,我们看到如果我们试图通过kwarg位置,我们得到一个错误:

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

我们必须显式传递kwarg参数作为关键字参数。

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

Python 2兼容的演示

*args (通常称为“星号”)和**kwargs (星号可以用“kwargs”来表示,但用“double-star kwargs”来表示)是Python使用***符号的常见习惯用法。 这些特定的variables名不是必需的(例如,你可以使用*foos**bars ),但是*foos约定可能会使你的Python编码者*foos

当我们不知道我们的函数将要接收什么或者我们可能传递多less个参数时,我们通常使用这些方法,有时甚至当单独命名每个variables会变得非常混乱和冗余(但是这通常是明确的比隐含更好)。

例1

以下函数描述如何使用它们,并演示行为。 请注意,命名的b参数将在第二个位置参数之前被消耗:

 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('eg 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('eg dict(**kwargs) (same as {kweg}) returns: \n{0}'.format( dict(**kwargs), kweg=kweg)) 

我们可以通过help(foo)来查看函数签名的在线帮助,告诉我们

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

我们用foo(1, 2, 3, 4, e=5, f=6, g=7)调用这个函数,

打印:

 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. eg max(a, b, *args) 4 eg dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns: {'e': 5, 'g': 7, 'f': 6} 

例2

我们也可以使用另一个函数来调用它,我们只提供a一个函数:

 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. eg max(a, b, *args) 100 eg dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns: {'c': 3, 'e': 5, 'd': 4, 'f': 6} 

例3:在装饰器中的实际使用

好的,也许我们还没有看到效用。 所以想象一下,在区分代码之前和/或之后,您有多个具有冗余代码的function。 为了说明的目的,以下命名函数仅仅是伪代码。

 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 

我们也许能够以不同的方式处理这个问题,但是我们当然可以用一个装饰器来提取冗余,所以我们下面的例子演示了*args**kwargs是非常有用的:

 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) 

通过分解我们的代码,哪些*args**kwargs允许我们做,我们减less了代码行,提高了可读性和可维护性,并且在我们的程序中具有唯一的规范位置。 如果我们需要改变这个结构的任何部分,我们就有一个地方去做每一个改变。

让我们先了解什么是位置参数和关键字参数。 以下是带位置参数的函数定义示例

 def test(a,b,c): print(a) print(b) print(c) test(1,2,3) #output: 1 2 3 

所以这是一个带位置参数的函数定义。 你也可以用关键字/命名参数来调用它:

 def test(a,b,c): print(a) print(b) print(c) test(a=1,b=2,c=3) #output: 1 2 3 

现在让我们研究一个关键字参数的函数定义的例子:

 def test(a=0,b=0,c=0): print(a) print(b) print(c) print('-------------------------') test(a=1,b=2,c=3) #output : 1 2 3 ------------------------- 

你也可以用位置参数来调用这个函数:

 def test(a=0,b=0,c=0): print(a) print(b) print(c) print('-------------------------') test(1,2,3) # output : 1 2 3 --------------------------------- 

所以我们现在知道函数定义与位置以及关键字参数。

现在让我们研究'*'运算符和'**'运算符。

请注意这些操作员可以在两个方面使用:

a) 函数调用

b) function定义

函数调用中使用“*”运算符和“**”运算符

让我们直接看一个例子,然后讨论它。

 def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2) print(a+b) my_tuple = (1,2) my_list = [1,2] my_dict = {'a':1,'b':2} # Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator sum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*' sum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*' sum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**' # output is 3 in all three calls to sum function. 

所以记住

当在函数调用中使用“*”或“**”运算符时 –

'*'运算符将数据结构(如列表或元组)解包为函数定义所需的参数。

'**'运算符将字典解包为函数定义所需的参数。

现在让我们研究在函数定义中使用的'*'运算符。 例:

 def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4)) sum = 0 for a in args: sum+=a print(sum) sum(1,2,3,4) #positional args sent to function sum #output: 10 

在函数定义中 ,“*”运算符将收到的参数打包成一个元组。

现在让我们看一个在函数定义中使用的“**”的例子:

 def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4}) sum=0 for k,v in args.items(): sum+=v print(sum) sum(a=1,b=2,c=3,d=4) #positional args sent to function sum 

在函数定义中 '**'运算符将收到的参数打包成字典。

所以记住:

函数调用中 ,“*”将元组或列表的数据结构解包为函数定义接收的位置或关键字参数。

在一个函数调用中 ,'**'将字典的数据结构解包为函数定义要接收的位置或关键字参数。

函数定义中 ,“*” 位置参数打包成一个元组。

函数定义中 ,“**” 关键字参数打包到字典中。

***在函数参数列表中有特殊的用法。 *暗示参数是一个列表,而**意味着参数是一个字典。 这允许函数使用任意数量的参数

从Python文档:

如果有更多的位置参数比forms参数槽更多,则会引发TypeErrorexception,除非使用语法“* identifier”的forms参数存在; 在这种情况下,该forms参数接收包含多余位置参数的元组(或者如果没有多余的位置参数,则为空元组)。

如果任何关键字参数不符合forms参数名称,则会引发TypeErrorexception,除非使用语法“** identifier”的forms参数存在; 在这种情况下,该forms参数将接收包含多余关键字参数的字典(使用关键字作为关键字并将参数值作为对应值),如果没有多余的关键字参数,则使用(新)空字典。

在Python 3.5中,您也可以在listdicttupleset显示中使用这种语法(有时也称为文字)。 见PEP 488:附加解包概括 。

 >>> (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链接。)

我想举一个别人没有提到的例子

*也可以解压一个发电机

来自Python3文档的一个例子

 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)) 

除了函数调用之外,* args和** kwargs在类层次结构中很有用,也避免了在Python中编写init方法。 在类似Django代码的框架中使用类似的用法。

例如,

 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()) 

此外,具有仅对该子类实例有意义的新属性的子类可以调用Base类init来卸载属性设置。 这是通过* args和** kwargs完成的。 主要使用kwargs,以便使用命名参数来读取代码。 例如,

 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') 

完整的代码在这里

在函数中使用这两个函数的一个很好的例子是:

 >>> def foo(*arg,**kwargs): ... print arg ... print kwargs >>> >>> a = (1, 2, 3) >>> b = {'aa': 11, 'bb': 22} >>> >>> >>> foo(*a,**b) (1, 2, 3) {'aa': 11, 'bb': 22} >>> >>> >>> foo(a,**b) ((1, 2, 3),) {'aa': 11, 'bb': 22} >>> >>> >>> foo(a,b) ((1, 2, 3), {'aa': 11, 'bb': 22}) {} >>> >>> >>> foo(a,*b) ((1, 2, 3), 'aa', 'bb') {} 

这个例子可以帮助你一次性记住*args**kwargs ,甚至superinheritance。

 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