标签:
# 关键字参数 def menu(wine, entree, dessert): print({‘wine‘: wine, ‘entree‘: entree, ‘dessert‘: dessert}) menu(‘frontenac‘, dessert=‘flan‘, entree=‘fish‘)
# 指定默认参数值 def menu(wine, entree, dessert=‘pudding‘): print({‘wine‘: wine, ‘entree‘: entree, ‘dessert‘: dessert}) menu(‘chardonnay‘, ‘chicken‘) # {‘dessert‘: ‘pudding‘, ‘entree‘: ‘chicken‘, ‘wine‘: ‘chardonnay‘} def nonbuggy(arg, result=None): if result is None: result = [] result.append(arg) print(result) nonbuggy(‘a‘) # [‘a‘] nonbuggy(‘b‘) # [‘b‘]
# 使用*收集位置参数 def print_args(*args): print(args) print_args(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‘) #(3, 2, 1, ‘wait!‘, ‘uh...‘) #(‘Need this one:‘, ‘cap‘) #(‘Need this one too:‘, ‘gloves‘) #(‘All the rest:‘, (‘scarf‘, ‘monocle‘, ‘mustache wax‘))
# 使用**收集关键字参数 #使用两个星号可以将参数收集到一个字典中, #参数的名字是字典的键,对应参数的值是字 典的值 def print_kwargs(**kwargs): print(kwargs) print_kwargs(wine=‘merlot‘, entree=‘mutton‘, dessert=‘macaroon‘) #{‘dessert‘: ‘macaroon‘, ‘entree‘: ‘mutton‘, ‘wine‘: ‘merlot‘}
标签:
原文地址:http://www.cnblogs.com/jzm17173/p/5207247.html