函数、参数2
1、关键字参数和默认值 ,格式:形参=实参/默认参数;使用关键字参数时,不用考虑函数调用参数的顺序,只要形参已经赋值即可;传递的参数数量<=函数中形参的数量
>>> def pro(name='Lawyer',action='assignment'): ####设定默认参数,如果调用该函数不传递参数,则使用默认值
print("%s is %s"%(name,action))
>>> pro(action='drinking',name="Bob") ###调用函数的时候,使用关键字参数,不用关注参数调用顺序(位置)
Bob is drinking
>>> pro() ###调用函数的时候,不传递参数,使用默认参数
Lawyer is assignment
>>> pro(name='Alice')###只传递一部分参数,另一部分使用默认参数
Alice is assignment
2、收集参数*args *收集其余的位置参数组成元组(a,b);**kwds **收集关键字参数组成字典形式{};
*收集其余的位置参数
>>> def print_params(*params):
print(params)
>>> print_params('Testing')
('Testing',) ###只用一个元素的元组后面有一个,
>>> print_params(1,2,3)
(1, 2, 3)
>>> print_params() ###不传递参数,返回一个空的元组
()
**收集关键字参数
>>> 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()
{}
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}
4、改写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属性