python支持函数从调用语句中收集任意数量的实参。在形参前可使用*和**。
1.*符号
例如:我们创建fruit函数的时候指定形参toppings前加*。
def fruit(*toppings): print(toppings)
那我们在调用上面函数时,就可以穿任意多的参数。例如:
fruit("banana") fruit("apple","orange")
输出如下所示:
('banana',) ('apple', 'orange')
形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。在上面语句可加for循环。
def fruit(*toppings): print(type(toppings)) for el in toppings: print('element: '+el) fruit("banana") fruit("apple", "orange")
输出如下:
<class 'tuple'> element: banana <class 'tuple'> element: apple element: orange
2.**符号
形参前加**,表示函数能够接受任意数量的键—值对。例如:
def build_profile(first1, last, **user_info): print(type(user_info)) profile = {} profile['first_name'] = first1 profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print(user_profile)
输出:
<class 'dict'> {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
由上可知,**user_info定义了一个名为user_info的字典。