传递任意数量的实参
形参前加一个 * ,Python会创建一个已形参为名的空元组,将所有收到的值都放到这个元组中:
defmake_pizza(*toppings): print("\nMakingapizzawiththefollowingtoppings:") fortoppingintoppings: print("-"+topping) make_pizza('pepperoni') make_pizza('mushroom','greenpeppers','extracheese')
不管函数收到多少实参,这种语法都管用。
1. 结合使用位置实参和任意数量实参
defmake_pizza(size,*toppings): print("\nMakinga"+str(size)+"-inchpizzawiththefollowingtoppings:") fortoppingintoppings: print("-"+topping) make_pizza(16,'pepperoni') make_pizza(12,'mushroom','greenpeppers','extracheese')
运行结果:
Makinga16-inchpizzawiththefollowingtoppings: -pepperoni Makinga12-inchpizzawiththefollowingtoppings: -mushroom -greenpeppers -extracheese
相关推荐:《Python视频教程》
2. 使用任意数量的关键字实参
defbuild_profile(first,last,**user_info): profile=dict() profile['first_name']=first profile['last_name']=last forkey,valueinuser_info.items(): profile[key]=value returnprofile user_profile=build_profile('albert','einstein',location='princeton',field='physic') print(user_profile)
形参**user_info中的两个星号让python创建了一个名为user_info的空字典。
下一篇