Python中的*args 和**kwargs的用法

args就是所有参数的数组,kwargs就是当你传入key=value是存储的字典,当函数的参数不确定时,可以使用*args 和kwargs,*args 没有key值,kwargs有key值

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

result:

arg: 1  another arg: two  another arg: 3

**kwargs:

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) # myarg2和myarg3被视为key, 感觉**kwargs可以当作容纳多个key和value的dictionary

result:

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

也可以用下面的形式:

def fun_var_args_call(arg1, arg2, arg3):      print "arg1:", arg1      print "arg2:", arg2      print "arg3:", arg3    args = ["two", 3] #list    fun_var_args_call(1, *args)

result:

arg1: 1      arg2: two      arg3: 3
def fun_var_args_call(arg1, arg2, arg3):          print "arg1:", arg1          print "arg2:", arg2          print "arg3:", arg3            kwargs = {"arg3": 3, "arg2": "two"} # dictionary            fun_var_args_call(1, **kwargs)

result:

arg1: 1      arg2:"two"      arg3:3

当所有传参为key=value形式将返回字典形式

Tags:

Del.icio.us Facebook TweetThis Digg StumbleUpon
Comments:1 (One) on this item

You might be interested in this: Salt dashboard_halite基础配置 用SVN的POST-COMMIT钩子自动部署代码到远端测试服务器 highcharts饼图将显示百分比改成具体传值数字 SecureCRT防止终端自动断开连接方法 salt state配置管理(二)


Copyright ??颓废的腰子技术Blog [Python中的*args 和**kwargs的用法], All Right Reserved. 2015. 人,总是很难改正自己的缺点,

Python中的*args 和**kwargs的用法

相关文章:

你感兴趣的文章:

标签云: