首页 > 其他 > 详细

函数参数

时间:2016-02-22 16:44:34      阅读:142      评论:0      收藏:0      [点我收藏+]
# 关键字参数
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

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!