说明
python中默认缺省参数,参数名传参,可变长度传参。
缺省参数
def foo(a,b=8):
print a,b
foo("leason") #leason 0
foo("leason",88) #def 88
参数名传参数
def foo(a,b):
print a,b
foo("hello",'world') # helloworld
foo(b='world',a="hello") # helloworld
可变长度参数
def foo(arg1,*tupleArg,**dictArg):
print "arg1=",arg1 #arg1=leason
print "tupleArg=",tupleArg #()
print "dictArg=",dictArg #[]
foo("leason")
可变长度参数*args
# 接收不定长参数*args
def fun_var_args(farg, *args):
print "arg:", farg
for value in args:
print "another arg:", value
fun_var_args(1, 2, 3) # *args可以当作可容纳多个变量组成的list
<< arg: 1
<< another arg: 2
<< another arg: 3
# 传收不定长参数*args
def fun_var_args_call(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
args = [2, 3] #list
fun_var_args_call(1, *args)
<< arg1: 1
<< arg2: 2
<< arg3: 3
可变长度**kwargs
# 接收不定长参数**kwargs
def fun_var_kwargs(arg1, **kwargs):
print "arg1:", arg1
for key in kwargs:
print "%s: %s" % (key, kwargs[key])
fun_var_kwargs(arg1=1, arg2=2, arg3=3) # **kwargs可以当作容纳多个key和value的dict
<< arg1: 1
<< arg2: 2
<< arg3: 3
# 传收不定长参数**kwargs
def fun_var_args_call(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
kwargs = {"arg3": 3, "arg2": 2} # dictionary
fun_var_args_call(1, **kwargs)
<< arg1: 1
<< arg2: 2
<< arg3: 3