码迷,mamicode.com
首页 > 编程语言 > 详细

python中的*args 和**kwargs

时间:2018-06-12 16:26:55      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:形式   style   函数   存储   fun   code   type   可变   int   

*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‘>

 

python中的*args 和**kwargs

标签:形式   style   函数   存储   fun   code   type   可变   int   

原文地址:https://www.cnblogs.com/HITSZ/p/9172931.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!