码迷,mamicode.com
首页 > 其他好文 > 详细

函数参数

时间:2016-02-22 16:45:52      阅读:139      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!