或者也可以说是如何在Python中使用变长的参数列表。
*args
和**kwargs着两个特殊语法在函数定义是用来传递一个不定长的参数列表。单个星号(*args)用于传递非keyworded,可变长度参数列表,而两个星号(**kwargs)则用于传递keyworded形式可变长度的参数列表。下面举例说明单个星号参数是如何传递非keyworded形式参数:(例子中传递一个位置参数,以及两个不定长的参数)
1 2 3 4 5 6 | def test_var_args(farg, * args): print "formal arg:" , farg for arg in args: print "another arg:" , arg test_var_args( 1 , "two" , 3 ) |
执行结果:
1 2 3 | formal arg: 1 another arg: two another arg: 3 |
紧接着演示如何使用**kwargs参数传递keyworded形式的参数:
1 2 3 4 5 6 | def test_var_kwargs(farg, * * kwargs): print "formal arg:" , farg for key in kwargs: print "another keyword arg: %s: %s" % (key, kwargs[key]) test_var_kwargs(farg = 1 , myarg2 = "two" , myarg3 = 3 ) |
执行结果:
1 2 3 | formal arg: 1 another keyword arg: myarg2: two another keyword arg: myarg3: 3 |
这里我们看到的是在函数定义时,使用两种不同的参数传递不定长的参数列表给函数。我们接着看如何在函数调用时使用这两个特殊的语法。
1 2 3 4 5 6 7 | def test_var_args_call(arg1, arg2, arg3): print "arg1:" , arg1 print "arg2:" , arg2 print "arg3:" , arg3 args = ( "two" , 3 ) test_var_args_call( 1 , * args) |
定义的时候传入三个参数,调用的时候却只有两个变量1和*args,执行结果:
1 2 3 | arg1: 1 arg2: two arg3: 3 |
再来一个例子演示如何在函数调用是使用**kwargs:
1 2 3 4 5 6 7 | def test_var_args_call(arg1, arg2, arg3): print "arg1:" , arg1 print "arg2:" , arg2 print "arg3:" , arg3 kwargs = { "arg3" : 3 , "arg2" : "two" } test_var_args_call( 1 , * * kwargs) |
执行结果:
1 2 3 | arg1: 1 arg2: two arg3: 3 |
———————————————————————
我们接着看这两个参数到底还有其他那些妙用:
1.比如类的继承:
1 2 3 4 5 6 7 8 9 10 | class Foo( object ): def __init__( self , value1, value2): # do something with the values print value1, value2 class MyFoo(Foo): def __init__( self , * args, * * kwargs): # do something else, don't care about the args print 'myfoo' super (MyFoo, self ).__init__( * args, * * kwargs) |
这样一个好处就是我么可以不必知道Foo信息就可以扩展该类。尤其是对于那些API有可能更改的情况下显得尤其方便。MyFoo可以传递所有参数给Foo.
2. 再看看**kwargs的一个妙用
1 2 3 | mynum = 1000 mystr = 'Hello World!' print "{mystr} New-style formatting is {mynum}x more fun!" . format ( * * locals ()) |
英文原文地址:http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
更多的讨论参考:http://stackoverflow.com/questions/3394835/args-and-kwargs