给形参指定默认值时,等号两边不要有空格
对于函数调用中的关键字实参,也应遵循这种约定:
任意数量的实参:
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
形参名 *toppings 中的星号让 Python 创建一个名为 toppings 的空元组,并将收到的所有值都封装到这个元组中。
函数体内的 print 语句通过生成输出来证明 Python 能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。
它以类似的方式处理不同的调用,注意, Python 将实参封装到一个元组中,即便函数只收到一个值也如此
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
Python 先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
任意数量关键字实参
def build_profile(first, last, **user_info):
""" 创建一个字典,其中包含我们知道的有关用户的一切 """
profile = {}
profile['first_name'] = first
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)
形参 **user_info 中的两个星号让 Python 创建一个名为 user_info 的空字典,并将收到的所有名称 — 值对都封装到这个字典中。