函数
位置参数
传 入参数的值是按照顺序依次复制过去的
关键字参数
调用参数时可以指定对应参数的名字,可以不考虑顺序
menu(entree='beef', dessert='bagel', wine='bordeaux')
指定默认参数值
>>> def menu(wine, entree, dessert='pudding'):
... return {'wine': wine, 'entree': entree, 'dessert': dessert}
# 不指定参数则使用默认参数
>>> menu('chardonnay', 'chicken')
{'dessert': 'pudding', 'wine': 'chardonnay', 'entree': 'chicken'}
# 指定参数则使用时会替代默认值
>>> menu('dunkelfelder', 'duck', 'doughnut')
{'dessert': 'doughnut', 'wine': 'dunkelfelder', 'entree': 'duck'}
*args
当参数被用在函数内部时,星号将一组可变数量的位置参数集合成参数值的元组
>>> def print_args(*args):
... print('Positional argument tuple:', args)
# 无参数调用函数,则什么也不会返回:
>>> print_args()
Positional argument tuple: ()
# 给函数传入的所有参数都会以元组的形式返回输出
>>> print_args(3, 2, 1, 'wait!', 'uh...')
Positional argument tuple: (3, 2, 1, 'wait!', 'uh...')
>>> def print_more(required1, required2, *args):
... print('Need this one:', required1)
... print('Need this one too:', required2)
... print('All the rest:', args)
...
>>> print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
Need this one: cap
Need this one too: gloves
All the rest: ('scarf', 'monocle', 'mustache wax')
**kwargs
使用两个星号可以将参数收集到一个字典中,参数的名字是字典的键,对应参数的值是字 典的值
>>> def print_kwargs(**kwargs):
... print('Keyword arguments:', kwargs)
>>> print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
Keyword arguments: {'dessert': 'macaroon', 'wine': 'merlot', 'entree': 'mutton'}