您的位置:首页 > 编程语言 > Python开发

python函数参数收集及其反转

2017-07-13 13:30 387 查看
*<-->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}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: