1. 程式人生 > >python中的*args 與 **kwarg形式的引數含義及用法

python中的*args 與 **kwarg形式的引數含義及用法

我在學習OpenStack的過程中遇到了大量的如下形式的程式碼段:

args['body'] = json.loads(request.body)
result = method(request=request, **args)

在這裡,**args是作為函式的實參,經過寫程式碼測試,發現要分兩種情況討論:

1.**args作為函式的形參:

def test(**args):
    print args
    
test(a='1', b=2)

執行結果:

[email protected]:/home/codes/kwargs# python 2.py
{'a': '1', 'b': 2}

結論:**args作為函式形參時,表示需要接收預設型別的引數。否則會報以下的錯誤

a = 1
def test(**args):
    print args

test(a)
Traceback (most recent call last):
  File "2.py", line 8, in <module>
    test(a)
TypeError: test() takes exactly 0 arguments (1 given)

2.**args作為函式的實參

args = {}
args['name'] = 'jack'

def test(name):
    print name

test(**args)

執行結果:

[email protected]:/home/codes/kwargs# python 2.py
jack

但是,如果我們把傳入引數改變一下

args = {}
args['name'] = 'jack'
args['id'] = 12345
def test(name):
    print name

test(**args)

結果為:

[email protected]:/home/codes/kwargs# python 2.py
Traceback (most recent call last):
  File "2.py", line 7, in <module>
    test(**args)
TypeError: test() got an unexpected keyword argument 'id'

這是由於**args被翻譯為了name = 'jack', 'id' = 12345的緣故。我們只需給test函式增加一個引數即可:

args = {}
args['name'] = 'jack'
args['id'] = 12345
def test(name, id):
    print name
    print id
test(**args)

結果:

[email protected]:/home/codes/kwargs# python 2.py
jack
12345

結論:**args作為形參時,表示將字典型別的資料轉化為預設預設引數,否則會出現如下的報錯

a = 1
def test(name, id):
    print name
    print id
test(**a)

報錯:

Traceback (most recent call last):
  File "2.py", line 8, in <module>
    test(**a)
TypeError: test() argument after ** must be a mapping, not int

總結: 當**args作為函式形參時,表示接收0個或任意個預設引數;當**args作為實參時,表示將字典轉換為預設引數