Skip navigation.

The InterMa Style

The Way of Freedom

Asterisk Argument in Python

在Python中的函数调用中有比较好玩的2个操作符:*和**,这2个操作符在静态语言中基本是看不到的。
她们使用方法也比较精巧,无论是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})

The schema of MTA-MDA-MUASLAMDUNK 和 樱木

Comments

bitstream 4. March 2007, 03:45

" In a function header, the *name must be after normal arguments and defaults, and **name must be last."

How to use Quote function:

  1. Select some text
  2. Click on the Quote link

Write a comment

Comment
(BBcode and HTML is turned off for anonymous user comments.)

If you can't read the words, press the small reload icon.


Smilies

January 2010
S M T W T F S
December 2009February 2010
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30