(轉)Python中的*args和**kwargs

來源:互聯網
上載者:User

標籤:nts   use   osi   optional   ems   lang   支援   test   擴充   

本文轉自:http://kodango.com/variable-arguments-in-python

糰子的小窩

Python是支援可變參數的,最簡單的方法莫過於使用預設參數,例如:

def test_defargs(one, two = 2):   print ‘Required argument: ‘, one   print ‘Optional argument: ‘, twotest_defargs(1)# result:# Required argument: 1# Optional argument: 2test_defargs(1, 3)# result:# Required argument: 1# Optional argument: 3

當然,本文章的主題並不是講預設參數,而是另外一種達到可變參數 (Variable Argument) 的方法:使用*args和**kwargs文法。其中,*args是可變的positional arguments列表,**kwargs是可變的keyword arguments列表。並且,*args必須位於**kwargs之前,因為positional arguments必須位於keyword arguments之前。

首先介紹兩者的基本用法。

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

def test_args(first, *args):   print ‘Required argument: ‘, first   for v in args:      print ‘Optional argument: ‘, vtest_args(1, 2, 3, 4)# result:# Required argument: 1# Optional argument:  2# Optional argument:  3# Optional argument:  4

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

def test_kwargs(first, *args, **kwargs):   print ‘Required argument: ‘, first   for v in args:      print ‘Optional argument (*args): ‘, v   for k, v in kwargs.items():      print ‘Optional argument %s (*kwargs): %s‘ % (k, v)test_kwargs(1, 2, 3, 4, k1=5, k2=6)# results:# Required argument:  1# Optional argument (*args):  2# Optional argument (*args):  3# Optional argument (*args):  4# Optional argument k2 (*kwargs): 6# Optional argument k1 (*kwargs): 5

*args和**kwargs文法不僅可以在函數定義中使用,同樣可以在函數調用的時候使用。不同的是,如果說在函數定義的位置使用*args和**kwargs是一個將參數pack的過程,那麼在函數調用的時候就是一個將參數unpack的過程了。下面使用一個例子來加深理解:

def test_args(first, second, third, fourth, fifth):    print ‘First argument: ‘, first    print ‘Second argument: ‘, second    print ‘Third argument: ‘, third    print ‘Fourth argument: ‘, fourth    print ‘Fifth argument: ‘, fifth# Use *argsargs = [1, 2, 3, 4, 5]test_args(*args)# results:# First argument:  1# Second argument:  2# Third argument:  3# Fourth argument:  4# Fifth argument:  5# Use **kwargskwargs = {    ‘first‘: 1,    ‘second‘: 2,    ‘third‘: 3,    ‘fourth‘: 4,    ‘fifth‘: 5}test_args(**kwargs)# results:# First argument:  1# Second argument:  2# Third argument:  3# Fourth argument:  4# Fifth argument:  5

使用*args和**kwargs可以非常方便的定義函數,同時可以加強擴充性,以便日後的代碼維護。

 

(轉)Python中的*args和**kwargs

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.