理解 Python 中的可變參數 *args 和 **kwargs:

  默認參數:

微笑 Python是支持可變參數的,最簡單的方法莫過於使用默認參數,例如:

 def getSum(x,y=5):
    print "x:", x
    print "y:", y
    print "x+y :", x + y


getSum(1)

# result:
# x: 1
# y: 5
# x+y : 6

getSum(1,7)

# result:
# x: 1
# y: 7
# x+y : 8

 

  可變參數:

另一種達到可變參數 (Variable Argument) 的方法:使用*args和**kwargs語法。其中,*args是可變的positional arguments列表,**kwargs是可變的keyword arguments列表。而且,*args必須位於**kwargs以前,由於positional arguments必須位於keyword arguments以前。html

微笑 首先介紹二者的基本用法。

下面一個例子使用*args,同時包含一個必須的參數:python

 1 def test_args(first, *args):
 2    print 'Required argument: ', first
 3    for v in args:
 4       print 'Optional argument: ', v
 5 
 6 test_args(1, 2, 3, 4)
 7 # result:
 8 # Required argument: 1
 9 # Optional argument:  2
10 # Optional argument:  3
11 # Optional argument:  4

 

下面一個例子使用*kwargs, 同時包含一個必須的參數和*args列表:面試

 1 def test_kwargs(first, *args, **kwargs):
 2    print 'Required argument: ', first
 3    for v in args:
 4       print 'Optional argument (*args): ', v
 5    for k, v in kwargs.items():
 6       print 'Optional argument %s (*kwargs): %s' % (k, v)
 7 
 8 test_kwargs(1, 2, 3, 4, k1=5, k2=6)
 9 # results:
10 # Required argument:  1
11 # Optional argument (*args):  2
12 # Optional argument (*args):  3
13 # Optional argument (*args):  4
14 # Optional argument k2 (*kwargs): 6
15 # Optional argument k1 (*kwargs): 5

 

*args和**kwargs語法不只能夠在函數定義中使用,一樣能夠在函數調用的時候使用。不一樣的是,若是說在函數定義的位置使用*args和**kwargs是一個將參數pack的過程,那麼在函數調用的時候就是一個將參數unpack的過程了。下面使用一個例子來加深理解:函數

 

 1 def test_args(first, second, third, fourth, fifth):
 2     print 'First argument: ', first
 3     print 'Second argument: ', second
 4     print 'Third argument: ', third
 5     print 'Fourth argument: ', fourth
 6     print 'Fifth argument: ', fifth
 7 
 8 # Use *args
 9 args = [1, 2, 3, 4, 5]
10 test_args(*args)
11 # results:
12 # First argument:  1
13 # Second argument:  2
14 # Third argument:  3
15 # Fourth argument:  4
16 # Fifth argument:  5
17 
18 # Use **kwargs
19 kwargs = {
20     'first': 1,
21     'second': 2,
22     'third': 3,
23     'fourth': 4,
24     'fifth': 5
25 }
26 
27 test_args(**kwargs)
28 # results:
29 # First argument:  1
30 # Second argument:  2
31 # Third argument:  3
32 # Fourth argument:  4
33 # Fifth argument:  5

 

版權全部,文章來源:http://www.cnblogs.com/sagecheng/p/5968762.html 學習

我的能力有限,本文內容僅供學習、探討,歡迎指正、交流。ui

.NET面試題解析(00)-開篇來談談面試 & 系列文章索引spa

  參考資料:

理解 Python 中的 *args 和 **kwargs:http://kodango.com/variable-arguments-in-pythoncode

相關文章
相關標籤/搜索