python中的*args 和**kwargs

*args是可变长参数,在函数内部以tuple形式存储;

def fun_var_args(farg, *args):
    print "arg:", farg
    print(type(args))

>>> fun_var_args(1, 'two', 3)
arg: 1
<type 'tuple'>

 

def fun_var_args(farg, *args): 
    print "arg:", farg 
    for value in args: 
        print "another arg:", value 

>>>fun_var_args(1, "two",3)

arg: 1
another arg: two
another arg: 3

 

对于参数**kwargs,输入时要指定key和value

def fun_var_kwargs(farg, **kwargs): 
    print "arg:", farg 
    for key in kwargs: 
        print "another keyword arg: %s: %s" % (key, kwargs[key])

>>>fun_var_kwargs(farg=1, myarg2='two', myarg3=3)

arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3

 

参数kwargs在函数内部存储为dict:

def fun_var_kwargs(farg, **kwargs): 
    print "arg:", farg 
    print(type(kwargs))

>>>fun_var_kwargs(farg=1, myarg2='two', myarg3=3)
arg: 1
<type 'dict'>

 

posted @ 2018-06-12 14:42  Apollo_zhanghongbo  阅读(252)  评论(0编辑  收藏  举报