Python-16-分配參數

與收集參數相反,這裏用*和**分配參數
 
def add(x, y):     
    return x + y
 使用*分配元組
params = (1, 2)
>>> add(*params) 
3
 
使用**分配字典中的值分配給關鍵字參數
def hello_3(greeting='Hello', name='world'):
  print('{}, {}!'.format(greeting, name))
>>> params = {'name': 'Sir Robin', 'greeting': 'Well met'} 
>>> hello_3(**params) 
Well met, Sir Robin!
 
若是在定義和調用函數時都使用*或**,將只傳遞元組或字典
相關文章
相關標籤/搜索