*
,這樣函數會接收一個參數列表。錯誤範例: 只接收一個,卻給 5 個參數
def super_func(args):
return sum(args)
super_func(1, 2, 3, 4, 5)
輸出:TypeError: super_func() takes 1 positional argument but 5 were given
輸出會跑出錯誤,只接收 1 個參數,卻給 5 個參數。
正確例子:可以加上 * args
def super_func(*args):
print(*args)
return sum(args)
super_func(1, 2, 3, 4, 5)
輸出: 1 2 3 4 5
拿掉星號,輸出為固定列表
def super_func(*args):
print(args)
return sum(args)
super_func(1, 2, 3, 4, 5)
輸出:(1, 2, 3, 4, 5)
def super_func(*args):
print(args)
return sum(args)
print(super_func(1, 2, 3, 4, 5))
輸出: (1, 2, 3, 4, 5)
15
**
在函數定義中的參數名稱之前添加兩個星號,住樣函數將接收到參數字典。例1.
def super_func(*args, **kwargs):
print(kwargs)
return sum(args)
print(super_func(1, 2, 3, 4, 5, num1=5, num2=10))
輸出:{'num1': 5, 'num2': 10}
15
例2.
def super_func(*args, **kwargs):
total = 0
for items in kwargs.values():
total += items
return sum(args) + total
print(super_func(1, 2, 3, 4, 5, num1=5, num2=10))
輸出:30