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

当函数的参数是可变参数是,使用*args和**kwargs。其中*args对应的可变参数不含key,而**kwargs对应的可变参数含有key。

*args的使用:

1 >>> def fun1(*args):
2 ...     for item in args:
3 ...             print item
4 ... 
5 >>> fun1(1, 'hello', True)
6 1
7 hello
8 True

或者:

 1 >>> def fun1_1(arg1, arg2, arg3):
 2 ...     print arg1
 3 ...     print arg2
 4 ...     print arg3
 5 ... 
 6 >>> args = ['hello', 3]
 7 >>> 
 8 >>> fun1_1('test', *args)
 9 test
10 hello
11 3

 

**kwargs的使用:

1 >>> def fun2(**kwargs):
2 ...     for k in kwargs:
3 ...             print "%s:%s" % (k, kwargs[k])
4 ... 
5 >>> fun2(hello=1, world=2, welcome=3)
6 world:2
7 welcome:3
8 hello:1

或者:

 1 >>> def fun2_2(arg1, hello, world):
 2 ...     print 'arg1:', arg1
 3 ...     print 'arg2:', hello
 4 ...     print 'arg3:', world
 5 ... 
 6 >>> kwargs = {'hello':3, 'world':2}
 7 >>> fun2_2(1, **kwargs)
 8 arg1: 1
 9 arg2: 3
10 arg3: 2

 

posted on 2016-03-29 13:57  stackhacks  阅读(988)  评论(0编辑  收藏  举报

导航