正过程:
def Test(a, b, c = 3, *args, ** kwarg):
print(a)
print(b)
print(c)
if args:
print("arg: ", args)
if kwarg:
print("kwarg: ", kwarg)
*arg会把多出来的位置参数转化为tuple
**kwarg会把关键字参数转化为dict
Test(1, 2, 3, 4, 5, keyword1 = "one", keyword2 = "two")
运行结果:
1
2
3
arg: (4, 5)
kwarg: {'keyword1': 'one', 'keyword2': 'two'}
逆过程:
def sum(a, b, c):
return a + b + c
a = [1, 2, 3]
# the * unpack list a
# 将元组或者列表分解为:1,2,3
print sum(*a)
>> 6
def sum(a, b, c):
return a + b + c
a = {'a': 1, 'b': 2, 'c': 3}
# the ** unpack dict a
#将字典分解为'a' = 1, 'b' = 2, 'c' = 3
print sum(**a)
>> 6
网友评论