随笔- 180  文章- 0  评论- 15 

转:http://blog.csdn.net/chenjinyu_tang/article/details/8136841

当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值。

还是直接来代码吧,废话少说

(1)*args例子:

1     def fun_var_args(farg, *args):  
2         print "arg:", farg  
3         for value in args:  
4             print "another arg:", value  
5       
6     fun_var_args(1, "two", 3) # *args可以当作可容纳多个变量组成的list  

result:

 1 arg: 1

2 another arg: two

3 another arg: 3  

(2)**kwargs例子:

1     def fun_var_kwargs(farg, **kwargs):  
2         print "arg:", farg  
3         for key in kwargs:  
4             print "another keyword arg: %s: %s" % (key, kwargs[key])  
5       
6       
7     fun_var_kwargs(farg=1, myarg2="two", myarg3=3) # myarg2和myarg3被视为key, 感觉**kwargs可以当作容纳多个key和value的dictionary  

result:

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

(3)也可以是用下面方式:

1     def fun_var_args_call(arg1, arg2, arg3):  
2         print "arg1:", arg1  
3         print "arg2:", arg2  
4         print "arg3:", arg3  
5       
6     args = ["two", 3] #list  
7       
8     fun_var_args_call(1, *args)  

result:

arg1: 1  
arg2: two  
arg3: 3 

(4)**kwargs方式二

1     def fun_var_args_call(arg1, arg2, arg3):  
2         print "arg1:", arg1  
3         print "arg2:", arg2  
4         print "arg3:", arg3  
5       
6     kwargs = {"arg3": 3, "arg2": "two"} # dictionary  
7       
8     fun_var_args_call(1, **kwargs)  

result:

    arg1: 1  
    arg2:"two"  
    arg3:3  

 

 posted on 2015-01-19 17:23  zmlctt  阅读(2289)  评论(0编辑  收藏