理解 Python 中的 *args 和 **kwargs
Python是支持可變參數(shù)的,最簡單的方法莫過于使用默認(rèn)參數(shù),例如:
def test_defargs(one, two = 2):print 'Required argument: ', oneprint 'Optional argument: ', twotest_defargs(1) # result: # Required argument: 1 # Optional argument: 2test_defargs(1, 3) # result: # Required argument: 1 # Optional argument: 3當(dāng)然,本文章的主題并不是講默認(rèn)參數(shù),而是另外一種達(dá)到可變參數(shù) (Variable Argument) 的方法:使用*args和**kwargs語法。其中,*args是可變的positional arguments列表,kwargs是可變的keyword arguments列表。并且,*args必須位于kwargs之前,因?yàn)閜ositional arguments必須位于keyword arguments之前。
首先介紹兩者的基本用法。
下面一個(gè)例子使用*args,同時(shí)包含一個(gè)必須的參數(shù):
''' 遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助, 群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書! ''' def test_args(first, *args):print 'Required argument: ', firstfor 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下面一個(gè)例子使用kwargs, 同時(shí)包含一個(gè)必須的參數(shù)和args列表:
''' 遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助, 群里還有不錯(cuò)的視頻學(xué)習(xí)教程和PDF電子書! ''' def test_kwargs(first, *args, **kwargs):print 'Required argument: ', firstfor v in args:print 'Optional argument (*args): ', vfor 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): 5args和**kwargs語法不僅可以在函數(shù)定義中使用,同樣可以在函數(shù)調(diào)用的時(shí)候使用。不同的是,如果說在函數(shù)定義的位置使用args和**kwargs是一個(gè)將參數(shù)pack的過程,那么在函數(shù)調(diào)用的時(shí)候就是一個(gè)將參數(shù)unpack的過程了。下面使用一個(gè)例子來加深理解:
def test_args(first, second, third, fourth, fifth):print 'First argument: ', firstprint 'Second argument: ', secondprint 'Third argument: ', thirdprint 'Fourth argument: ', fourthprint 'Fifth argument: ', fifth# Use *args args = [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 **kwargs kwargs = {'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可以非常方便的定義函數(shù),同時(shí)可以加強(qiáng)擴(kuò)展性,以便日后的代碼維護(hù)。
總結(jié)
以上是生活随笔為你收集整理的理解 Python 中的 *args 和 **kwargs的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 用turtle库画围棋棋盘
- 下一篇: python 并集union, 交集in