**(双星/星号)和*(星号/星号)对参数有什么作用?

**(双星/星号)和*(星号/星号)对参数有什么作用?

在下面的方法定义,什么是*和**为做param2?


def foo(param1, *param2):

def bar(param1, **param2):


哆啦的时光机
浏览 843回答 5
5回答

汪汪一只猫

的*args和**kwargs是一种常见的成语,以允许参数,以作为部分所述功能的任意数量的多个上定义函数 Python文档英寸该*args给你的所有函数参数为一个元组:In [1]: def foo(*args):    ...:     for a in args:    ...:         print a   ...:             ...:         In [2]: foo(1)1In [4]: foo(1,2,3)123该**kwargs会给你所有的 关键字参数除了那些与作为字典的形式参数。In [5]: def bar(**kwargs):    ...:     for a in kwargs:    ...:         print a, kwargs[a]    ...:             ...:         In [6]: bar(name='one', age=27)age 27name 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):&nbsp; &nbsp; print("x=" + str(x))&nbsp; &nbsp; print("y=" + str(y))&nbsp; &nbsp; print("z=" + str(z))你可以这样做:>>> mylist = [1,2,3]>>> foo(*mylist)x=1y=2z=3>>> mydict = {'x':1,'y':2,'z':3}>>> foo(**mydict)x=1y=2z=3>>> mytuple = (1, 2, 3)>>> foo(*mytuple)x=1y=2z=3注意:键的名称mydict必须与函数的参数完全相同foo。否则会抛出TypeError:>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}>>> foo(**mydict)Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>TypeError: foo() got an unexpected keyword argument 'badnews'

DIEA

单*表示可以有任意数量的额外位置参数。foo()可以调用像foo(1,2,3,4,5)。在foo()的主体中,param2是一个包含2-5的序列。双**表示可以有任意数量的额外命名参数。bar()可以调用像bar(1, a=2, b=3)。在bar()的主体中,param2是一个包含{'a':2,'b':3}的字典使用以下代码:def foo(param1, *param2):&nbsp; &nbsp; print(param1)&nbsp; &nbsp; print(param2)def bar(param1, **param2):&nbsp; &nbsp; print(param1)&nbsp; &nbsp; print(param2)foo(1,2,3,4,5)bar(1,a=2,b=3)输出是1(2, 3, 4, 5)1{'a': 2, 'b': 3}

莫回无

这是什么**(双星)和*(明星)的参数做它们允许定义函数以接受并允许用户传递任意数量的参数,position(*)和keyword(**)。定义功能*args允许任意数量的可选位置参数(参数),这些参数将分配给名为的元组args。**kwargs允许任意数量的可选关键字参数(参数),这些参数将在名为dict的dict中kwargs。您可以(并且应该)选择任何适当的名称,但是如果参数的目的是非特定语义,args并且kwargs是标准名称。扩展,传递任意数量的论点您还可以分别使用*args和**kwargs传递列表(或任何可迭代)和dicts(或任何映射)中的参数。接收参数的函数不必知道它们正在被扩展。例如,Python 2的xrange没有明确指望*args,但因为它需要3个整数作为参数:>>> x = xrange(3) # create our *args - an iterable of 3 integers>>> xrange(*x)&nbsp; &nbsp; # expand herexrange(0, 2, 2)再举一个例子,我们可以使用dict扩展str.format:>>> foo = 'FOO'>>> bar = 'BAR'>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())'this is foo, FOO and bar, BAR'Python 3中的新功能:使用仅关键字参数定义函数您可以在-&nbsp;之后只有关键字参数*args&nbsp;- 例如,此处kwarg2必须作为关键字参数给出 - 而不是位置:def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs):&nbsp;&nbsp; &nbsp; 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):&nbsp;&nbsp; &nbsp; 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):&nbsp; File "<stdin>", line 1, in <module>TypeError: foo() takes from 1 to 2 positional arguments&nbsp;&nbsp; &nbsp; but 5 positional arguments (and 1 keyword-only argument) were given同样,更简单地说,这里我们需要kwarg通过名称给出,而不是位置:def bar(*, kwarg=None):&nbsp;&nbsp; &nbsp; return kwarg在这个例子中,我们看到如果我们尝试通过kwarg位置传递,我们会收到一个错误:>>> bar('kwarg')Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>TypeError: bar() takes 0 positional arguments but 1 was given我们必须显式地将kwarg参数作为关键字参数传递。>>> bar(kwarg='kwarg')'kwarg'Python 2兼容演示*args(通常说“star-args”)和**kwargs(明星可以通过说“kwargs”暗示,但明确表示“双星kwargs”)是Python使用*和**表示法的常用习语。这些特定的变量名称不是必需的(例如,您可以使用*foos和**bars),但偏离惯例可能会激怒您的Python同事。当我们不知道我们的函数将接收什么或者我们可能传递多少个参数时,我们通常会使用这些,有时即使分别命名每个变量也会变得非常混乱和冗余(但这种情况通常是明确的比隐含更好。例1以下函数描述了它们的使用方式,并演示了行为。请注意,命名b参数将在第二个位置参数之前使用:def foo(a, b=10, *args, **kwargs):&nbsp; &nbsp; '''&nbsp; &nbsp; this function takes required argument a, not required keyword argument b&nbsp; &nbsp; and any number of unknown positional arguments and keyword arguments after&nbsp; &nbsp; '''&nbsp; &nbsp; print('a is a required argument, and its value is {0}'.format(a))&nbsp; &nbsp; print('b not required, its default value is 10, actual value: {0}'.format(b))&nbsp; &nbsp; # we can inspect the unknown arguments we were passed:&nbsp; &nbsp; #&nbsp; - args:&nbsp; &nbsp; print('args is of type {0} and length {1}'.format(type(args), len(args)))&nbsp; &nbsp; for arg in args:&nbsp; &nbsp; &nbsp; &nbsp; print('unknown arg: {0}'.format(arg))&nbsp; &nbsp; #&nbsp; - kwargs:&nbsp; &nbsp; print('kwargs is of type {0} and length {1}'.format(type(kwargs),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; len(kwargs)))&nbsp; &nbsp; for kw, arg in kwargs.items():&nbsp; &nbsp; &nbsp; &nbsp; print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))&nbsp; &nbsp; # But we don't have to know anything about them&nbsp;&nbsp; &nbsp; # to pass them to other functions.&nbsp; &nbsp; print('Args or kwargs can be passed without knowing what they are.')&nbsp; &nbsp; # max can take two or more positional args: max(a, b, c...)&nbsp; &nbsp; print('e.g. max(a, b, *args) \n{0}'.format(&nbsp; &nbsp; &nbsp; max(a, b, *args)))&nbsp;&nbsp; &nbsp; kweg = 'dict({0})'.format( # named args same as unknown kwargs&nbsp; &nbsp; &nbsp; ', '.join('{k}={v}'.format(k=k, v=v)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for k, v in sorted(kwargs.items())))&nbsp; &nbsp; print('e.g. dict(**kwargs) (same as {kweg}) returns: \n{0}'.format(&nbsp; &nbsp; &nbsp; 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 1b not required, its default value is 10, actual value: 2args is of type <type 'tuple'> and length 2unknown arg: 3unknown arg: 4kwargs is of type <type 'dict'> and length 3unknown kwarg - kw: e, arg: 5unknown kwarg - kw: g, arg: 7unknown kwarg - kw: f, arg: 6Args or kwargs can be passed without knowing what they are.e.g. max(a, b, *args)&nbsp;4e.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns:&nbsp;{'e': 5, 'g': 7, 'f': 6}例2我们也可以使用我们刚刚提供的另一个函数来调用它a:def bar(a):&nbsp; &nbsp; b, c, d, e, f = 2, 3, 4, 5, 6&nbsp; &nbsp; # dumping every local variable into foo as a keyword argument&nbsp;&nbsp; &nbsp; # by expanding the locals dict:&nbsp; &nbsp; foo(**locals())&nbsp;bar(100) 打印:a is a required argument, and its value is 100b not required, its default value is 10, actual value: 2args is of type <type 'tuple'> and length 0kwargs is of type <type 'dict'> and length 4unknown kwarg - kw: c, arg: 3unknown kwarg - kw: e, arg: 5unknown kwarg - kw: d, arg: 4unknown kwarg - kw: f, arg: 6Args or kwargs can be passed without knowing what they are.e.g. max(a, b, *args)&nbsp;100e.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns:&nbsp;{'c': 3, 'e': 5, 'd': 4, 'f': 6}例3:装饰器中的实际用法好吧,也许我们还没有看到效用。因此,假设在差分代码之前和/或之后,您有多个具有冗余代码的函数。以下命名函数仅用于说明目的的伪代码。def foo(a, b, c, d=0, e=100):&nbsp; &nbsp; # imagine this is much more code than a simple function call&nbsp; &nbsp; preprocess()&nbsp;&nbsp; &nbsp; differentiating_process_foo(a,b,c,d,e)&nbsp; &nbsp; # imagine this is much more code than a simple function call&nbsp; &nbsp; postprocess()def bar(a, b, c=None, d=0, e=100, f=None):&nbsp; &nbsp; preprocess()&nbsp; &nbsp; differentiating_process_bar(a,b,c,d,e,f)&nbsp; &nbsp; postprocess()def baz(a, b, c, d, e, f):&nbsp; &nbsp; ... and so on我们可能能够以不同的方式处理这个问题,但我们当然可以使用装饰器提取冗余,因此下面的示例演示了如何*args以及**kwargs非常有用:def decorator(function):&nbsp; &nbsp; '''function to wrap other functions with a pre- and postprocess'''&nbsp; &nbsp; @functools.wraps(function) # applies module, name, and docstring to wrapper&nbsp; &nbsp; def wrapper(*args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; # again, imagine this is complicated, but we only write it once!&nbsp; &nbsp; &nbsp; &nbsp; preprocess()&nbsp; &nbsp; &nbsp; &nbsp; function(*args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; postprocess()&nbsp; &nbsp; return wrapper现在,每个包装的函数都可以更简洁地编写,因为我们已经考虑了冗余:@decoratordef foo(a, b, c, d=0, e=100):&nbsp; &nbsp; differentiating_process_foo(a,b,c,d,e)@decoratordef bar(a, b, c=None, d=0, e=100, f=None):&nbsp; &nbsp; differentiating_process_bar(a,b,c,d,e,f)@decoratordef baz(a, b, c=None, d=0, e=100, f=None, g=None):&nbsp; &nbsp; differentiating_process_baz(a,b,c,d,e,f, g)@decoratordef quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):&nbsp; &nbsp; differentiating_process_quux(a,b,c,d,e,f,g,h)通过分解我们的代码*args并**kwargs允许我们这样做,我们减少了代码行数,提高了可读性和可维护性,并在程序中为逻辑提供了唯一的规范位置。如果我们需要改变这个结构的任何部分,我们有一个地方可以进行每次更改。

叮当猫咪

让我们首先了解什么是位置参数和关键字参数。下面是使用Positional参数的函数定义示例。def test(a,b,c):&nbsp; &nbsp; &nbsp;print(a)&nbsp; &nbsp; &nbsp;print(b)&nbsp; &nbsp; &nbsp;print(c)test(1,2,3)#output:123所以这是一个带位置参数的函数定义。您也可以使用关键字/命名参数调用它:def test(a,b,c):&nbsp; &nbsp; &nbsp;print(a)&nbsp; &nbsp; &nbsp;print(b)&nbsp; &nbsp; &nbsp;print(c)test(a=1,b=2,c=3)#output:123现在让我们用关键字参数研究函数定义的示例:def test(a=0,b=0,c=0):&nbsp; &nbsp; &nbsp;print(a)&nbsp; &nbsp; &nbsp;print(b)&nbsp; &nbsp; &nbsp;print(c)&nbsp; &nbsp; &nbsp;print('-------------------------')test(a=1,b=2,c=3)#output :123-------------------------您也可以使用位置参数调用此函数:def test(a=0,b=0,c=0):&nbsp; &nbsp; print(a)&nbsp; &nbsp; print(b)&nbsp; &nbsp; print(c)&nbsp; &nbsp; print('-------------------------')test(1,2,3)# output :123---------------------------------所以我们现在知道具有位置和关键字参数的函数定义。现在让我们研究'*'运算符和'**'运算符。请注意,这些运营商可以在两个方面使用:a)函数调用b)功能定义在函数调用中使用'*'运算符和'**'运算符。让我们直接举一个例子然后讨论它。def sum(a,b):&nbsp; #receive args from function calls as sum(1,2) or sum(a=1,b=2)&nbsp; &nbsp; 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 '*' operatorsum(*my_tuple)&nbsp; &nbsp;# becomes same as sum(1,2) after unpacking my_tuple with '*'sum(*my_list)&nbsp; &nbsp; # becomes same as sum(1,2) after unpacking my_list with&nbsp; '*'sum(**my_dict)&nbsp; &nbsp;# becomes same as sum(a=1,b=2) after unpacking by '**'&nbsp;# 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))&nbsp; &nbsp; sum = 0&nbsp; &nbsp; for a in args:&nbsp; &nbsp; &nbsp; &nbsp; sum+=a&nbsp; &nbsp; print(sum)sum(1,2,3,4)&nbsp; #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})&nbsp; &nbsp; sum=0&nbsp; &nbsp; for k,v in args.items():&nbsp; &nbsp; &nbsp; &nbsp; sum+=v&nbsp; &nbsp; print(sum)sum(a=1,b=2,c=3,d=4) #positional args sent to function sum在函数定义中,'**'运算符将接收的参数打包到字典中。所以请记住:在函数调用中,'*' 将元组或列表的数据结构解包为要由函数定义接收的位置或关键字参数。在函数调用中,'**' 将字典的数据结构解包为要由函数定义接收的位置或关键字参数。在函数定义中,'*' 将位置参数打包到元组中。在函数定义中,'**' 将关键字参数打包到字典中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python