今天爱分享给大家带来Python中**和*的作用是什么【面试题详解】,希望能够帮助到大家。
*args和**kwargs允许函数拥有任意数量的参数,具体可以查看 more on defining functions
*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的另一个用法是用于函数调用时的参数列表解包(unpack)
first, *rest = [1,2,3,4] first, *l, last = [1,2,3,4]