Sunday, January 30, 2011

Python的可变参数*args与**kwargs

From:http://hi.baidu.com/zengjianyuan/blog/item/6a1cd400f6a6261c728b65b1.html

*args是个tuple,**kwargs是个dict。

[zjy@zjy Code]$ cat aa.py
def foo(*args,**kwargs):
print('args: %s' % str(args)),
print('kwargs: %s' % str(kwargs))  
foo(2,3,4)         #print "args: (2,3,4) kwargs: {}"
foo(a=4,b=5)         #print "args: () kwargs: {'a': 4, 'b': 5}
foo(2,3,a=4,b=5)     #print "args: (2,3) kwargs: {'a': 4, 'b': 5}
#foo(a=4,b=5,2,3)     #raise SyntaxError  
x = (2,3,4)
foo(7,8,9,x)         #print "args: (7,8,9,(2,3,4)) kwargs: {}"
foo(7,8,9,*x)         #print "args: (7,8,9,2,3,4) kwargs: {}"

*args和**kwargs并用时,*args必须放在**kwargs的前面。

转自:http://dongua81.blog.163.com/blog/static/55795320095298314707/

No comments:

Post a Comment