*<-->tuple
和**<-->dict
的使用分为两种情况,一种是函数调用,另外一种是函数定义。
Function call
*tuple means “treat the elements of this tuple as positional arguments to this function call.”
def foo(x, y):
print(x, y)
>>> t = (1, 2)
>>> foo(*t)
1 2
**dict means “treat the key-value pairs in the dictionary as additional named arguments to this function call.”
def foo(x, y):
print(x, y)
>>> d = {'x':1, 'y':2}
>>> foo(**d)
1 2
Function signature
*tuple means “take all additional positional aruments to this function and pack them into this parameter as a tuple.”
def foo(*x):
print(x)
>>> foo(1, 2)
(1, 2)
**dict means “take all additional named arguments to this function and insert them into this parameter as dictionary entries.”
def foo(**d):
print(d)
>>> foo(x=1, y=2)
{'y': 2, 'x': 1}