大话Python中*args和**kargs的使用

时间:2021-12-12 20:54:09

对于初学者来说,看到*args和**kargs就头大,到底它们有何用处,怎么使用?这篇文章将为你揭开可变参数的神秘面纱

1.*args 实质就是将函数传入的参数,存储在元组类型的变量args当中

def fun_var_args(farg, *args):
print "arg:", farg
for value in args:
print "other arg:", value fun_var_args(1, "two", 3) arg: 1
other arg: two
other arg: 3

2.第二种场景:

def fun_input_list(var1,var2,var3):
print var1,var2,var3 var_list=["second",3]
fun_input_list(1,*var_list) 1 second 3

3.**kargs 实质就是将函数的参数和值,存储在字典类型的kargs变量中

def fun_var_kargs(farg,**kargs):
print "firsr value %s"% farg
for key in kargs.keys():
print kargs[key]
fun_var_kargs(1,var1="second",var2=35,var3="third")
firsr value 1
second
third
35

4.**kargs的第二种使用场景

def fun_input_dic(var1,var2=2,var3=3):
print var1,var2,var3 dic_input={"var2":2,"var3":"third"}
fun_input_dic(1,**dic_input)
1 2 third