代码艺术家
Code artist

很喜欢释迦牟尼佛的一句话:“无论你遇见谁,他都是你生命该出现的人,绝非偶然,他一定教会你一些什么”。

有问题 问我 问Google

Python * args 和 ** kwargs那点事


1,前言:一般出现*args 和 **kwargs,首先给我想到的是C语言的指针,真的。估计这是用C编写Python没有有阉割干净的缘故。

2,正题: 什么时候用这两个参数呢,我们通常见得最多的时候是作为函数的参数,当函数的参数不确定时,可以使用*args和 **kwargs,*args 没有key值,**kwargs 有key值。

3,例子

def args_test(param1,*args):
    print "first param is:",param1
    index = 1
    for value in args:
       print "the "+str(index)+" is:"+str(value)
       index += 1

def kwargs_test(param1,**kwargs):
    print "the first param is: ",param1
    for key in kwargs:
        print "the key is: %s, and the value is: %s" %(key,kwargs[key])

if __name__ == "__main__":
    args_test('ha',1,'a','b','d','test')
    kwargs_test('hi,kwargs',tom = 30,lilei = 28,hamei = 29)

程序结果:

first param is: ha
the 1 is:1
the 2 is:a
the 3 is:b
the 4 is:d
the 5 is:test
the first param is:  hi,kwargs
the key is: lilei, and the value is: 28
the key is: hamei, and the value is: 29
the key is: tom, and the value is: 30 

4,总结:*args可以传入列表,元组。**kwargs可以传入字典作为参数。

posted @ 2017-03-31 23:06  Jason‘  阅读(8747)  评论(0编辑  收藏  举报