函数

位置参数

传 入参数的值是按照顺序依次复制过去的

关键字参数

调用参数时可以指定对应参数的名字,可以不考虑顺序

menu(entree='beef', dessert='bagel', wine='bordeaux')

指定默认参数值

  1. >>> def menu(wine, entree, dessert='pudding'):
  2. ... return {'wine': wine, 'entree': entree, 'dessert': dessert}
  3. # 不指定参数则使用默认参数
  4. >>> menu('chardonnay', 'chicken')
  5. {'dessert': 'pudding', 'wine': 'chardonnay', 'entree': 'chicken'}
  6. # 指定参数则使用时会替代默认值
  7. >>> menu('dunkelfelder', 'duck', 'doughnut')
  8. {'dessert': 'doughnut', 'wine': 'dunkelfelder', 'entree': 'duck'}

*args

当参数被用在函数内部时,星号将一组可变数量的位置参数集合成参数值的元组

  1. >>> def print_args(*args):
  2. ... print('Positional argument tuple:', args)
  3. # 无参数调用函数,则什么也不会返回:
  4. >>> print_args()
  5. Positional argument tuple: ()
  6. # 给函数传入的所有参数都会以元组的形式返回输出
  7. >>> print_args(3, 2, 1, 'wait!', 'uh...')
  8. Positional argument tuple: (3, 2, 1, 'wait!', 'uh...')
  9. >>> def print_more(required1, required2, *args):
  10. ... print('Need this one:', required1)
  11. ... print('Need this one too:', required2)
  12. ... print('All the rest:', args)
  13. ...
  14. >>> print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
  15. Need this one: cap
  16. Need this one too: gloves
  17. All the rest: ('scarf', 'monocle', 'mustache wax')

**kwargs

使用两个星号可以将参数收集到一个字典中,参数的名字是字典的键,对应参数的值是字 典的值

  1. >>> def print_kwargs(**kwargs):
  2. ... print('Keyword arguments:', kwargs)
  3. >>> print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
  4. Keyword arguments: {'dessert': 'macaroon', 'wine': 'merlot', 'entree': 'mutton'}