Rob*_*oon 12 python function-parameter argument-unpacking
我知道星号在Python中的函数定义中是什么意思.
不过,我经常会看到使用参数调用函数的星号:
def foo(*args, **kwargs):
first_func(args, kwargs)
second_func(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
第一个和第二个函数调用有什么区别?
Lit*_*leQ 20
args = [1,2,3]
func(*args) == func(1,2,3)
变量作为参数从列表(或任何其他序列类型)中解压缩
func(args) == func([1,2,3])
列表被传递
kwargs = dict(a=1,b=2,c=3)
func(kwargs) == func({'a':1, 'b':2, 'c':3})
dict通过了
func(*kwargs) == func(('a','b','c'))
(key,value)作为命名参数从dict(或任何其他映射类型)中解压缩
不同之处在于参数如何传递给被调用的函数.当你使用时*
,参数被解压缩(如果它们是列表或元组) - 另外,它们只是按原样传入.
以下是差异的示例:
>>> def add(a, b):
... print a + b
...
>>> add(*[2,3])
5
>>> add([2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (1 given)
>>> add(4, 5)
9
Run Code Online (Sandbox Code Playgroud)
当我用参数作为前缀时*
,它实际上将列表解压缩为两个单独的参数,这些参数被传递到add
as a
和b
.没有它,它只是作为单个参数传递给列表.
字典也是如此**
,除了它们作为命名参数而不是有序参数传递.
>>> def show_two_stars(first, second='second', third='third'):
... print "first: " + str(first)
... print "second: " + str(second)
... print "third: " + str(third)
>>> show_two_stars('a', 'b', 'c')
first: a
second: b
third: c
>>> show_two_stars(**{'second': 'hey', 'first': 'you'})
first: you
second: hey
third: third
>>> show_two_stars({'second': 'hey', 'first': 'you'})
first: {'second': 'hey', 'first': 'you'}
second: second
third: third
Run Code Online (Sandbox Code Playgroud)