Asterisk Argument in Python
Saturday, 20. January 2007, 04:21:37
她们使用方法也比较精巧,无论是PP3还是PitN2中都讲解得不太清楚,其实可以用一句话来概括她们的作用:
作为形参的Asterisk做拼合,作为实参的Asterisk做分拆。
下边举几个例子说明一下:
- 拼合:
def foo(a, *b): print a, b foo(1, 2, 3, 4) # the result is: 1 (2, 3, 4)
- 分拆:
def foo(a, b, c, d): print a, b, c, d foo(1, *(2, 3, 4)) # the result is: 1 2 3 4
- 先拆再拼:
def foo(a, *b): print a, b foo(1, *(2, 3, 4)) # the result is: 1 (2, 3, 4)
**的情况和*一样,只不过*用于Set,而**用于Dictionary,同时形参名称要匹配。
最后给一个PP3中的代码片段,你能猜出结果吗?
a=1; b=2; c=3; d=4; e=5
def func(a, *ps, **ks):
print a, ps, ks
func(a, b, c=1, *(d, e), **{'f':2})







bitstream # 4. March 2007, 03:45