一、關鍵字參數和默認值 ,格式:形參=實參/默認參數;使用關鍵字參數時,不用考慮函數調用參數的順序,只要形參已經賦值便可;傳遞的參數數量<=函數中形參的數量數組
>>> def pro(name='Lawyer',action='assignment'): ####設定默認參數,若是調用該函數不傳遞參數,則使用默認值
print("%s is %s"%(name,action))app
>>> pro(action='drinking',name="Bob") ###調用函數的時候,使用關鍵字參數,不用關注參數調用順序(位置)
Bob is drinking
>>> pro() ###調用函數的時候,不傳遞參數,使用默認參數
Lawyer is assignment函數
>>> pro(name='Alice')###只傳遞一部分參數,另外一部分使用默認參數
Alice is assignmentspa
二、收集參數*args *收集其他的位置參數組成元組(a,b);**kwds **收集關鍵字參數組成字典形式{};blog
*收集其他的位置參數ip
>>> def print_params(*params):
print(params)it
>>> print_params('Testing')
('Testing',) ###只用一個元素的元組後面有一個,
>>> print_params(1,2,3)
(1, 2, 3)io
>>> print_params() ###不傳遞參數,返回一個空的元組
()遍歷
**收集關鍵字參數im
>>> def print_params_3(**params):
print(params)
>>> print_params_3(x=1,y=2,z=3)
{'x': 1, 'y': 2, 'z': 3}
>>> print_params_3()
{}
三、位置參數、關鍵字參數、*params、**params的混合使用;位置參數必定要放在關鍵字參數、收集參數以前
###位置參數必定要放在關鍵字參數、收集參數以前
>>> def print_params_4(x,y,z=3,*pospar,**keypar):
print(x,y,z)
print(pospar)
print(keypar)
###運行順序:x=1,y=2,關鍵字參數z=4,其他的位置參數5,6被*popbar收集成(5,6),關鍵字參數被**keybar收集成{'foo': 1, 'bar': 2}
>>> print_params_4(1,2,4,5,6,foo=1,bar=2)
1 2 4
(5, 6)
{'foo': 1, 'bar': 2}
四、改寫store函數,以前store函數只能接受處理一個參數;如今改寫成處理多個參數
def init(data):
data['first'] = {}
data['middle'] = {}
data['third'] = {}
def lookup(data,label,name):
return data[label][name]
def store(data,*full_names):
for full_name in full_names:
names = full_name.split()
if len(names)==2:
names.insert(1,'')
labels = ['first','middle','third']
for label,name in zip(labels,names):
try:
people = lookup(data,label,name)
except KeyError as err:
print("KeyError:"+str(err))
people = None
finally:
if people:
data[label][name].append(full_name)
else:
data[label][name]=full_name
return data
if __name__ == '__main__':
mynumbs_1 = {}
mynumbs_2 = {}
mynumbs_3 = {}
init(mynumbs_1)
init(mynumbs_2)
init(mynumbs_3)
mynumbs_1=store(mynumbs_1, 'Li zhang yang')###傳入一個full_names參數,*full_names將後面的位置參數組合成('Li zhang yang',)
###傳入兩個full_names參數,*full_names將後面的兩個位置參數組合成('Li zhang yang','zhang hang hang')
mynumbs_2 = store(mynumbs_2, 'Li zhang yang','zhang hang hang')
full_names = ('Li zhang yang', 'zhang hang hang')###相似*full_names的反應用
mynumbs_3 = store(mynumbs_3, *full_names)
print(mynumbs_1,'\n',mynumbs_2,'\n',mynumbs_3)
mynumbs_4 =store(mynumbs_3,('Li zhang yang', 'zhang hang hang'))
###不能直接傳tuple做爲參數,會報錯由於*會把後面這個位置參數組合成(('Li zhang yang', 'zhang hang hang'),)組成了set序列
遍歷full_names時('Li zhang yang', 'zhang hang hang')會被當成一個元素處理,tuple元素沒有split屬性