python: *args **kwargs

1.*args

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

# 等价于
args = ["two", 3] #list  
fun_var_args_call(1, *args)  
result:
arg: 1  
another arg: two  
another arg: 3

2.**kwargs

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

#等价于
kwargs = {"arg3": 3, "arg2": "two"} # dictionary  
fun_var_args_call(1, **kwargs)  
result:
arg: 1  
another keyword arg: myarg2: two  
another keyword arg: myarg3: 3  

shiyang6017
158 声望59 粉丝