python可變長參數(非關鍵字及關鍵字參數)

來源:互聯網
上載者:User

標籤:blog   word   輸入   列印   多次   key   log   功能   不同的   

可變長參數存在的意義是:每次調用一個函數處理不同量的參數輸入。即,參數在調用之前輸入的參數數量是未知的,或者多次調用該函數,每次的參數輸入的量是不一致的;

可變長參數分為非關鍵字和關鍵字類型,分別對應元組和字典,如下定義一個類,功能是列印出輸入的函數:

 1 >>> class Test: 2     def keyword(self,a,b,*non_keyword,**keyword): 3         print(‘a is ‘,a) 4         print(‘b is ‘,b) 5         print(‘non_keyword‘,non_keyword) 6         for key in keyword: 7             print("‘%s‘:%s" % (key,str(keyword[key]))) 8 >>> test = Test() 9 >>> dis = test.keyword(‘a‘,‘b‘,(‘c‘,‘d‘),e=‘e‘,f=‘f‘)10 a is  a11 b is  b12 non_keyword ((‘c‘, ‘d‘),)13 ‘e‘:e14 ‘f‘:f

以上的輸入時一次輸入的情形,當再次調用,輸入不同的數量的參數時,依然可以列印出:

1 >>> test0 = Test()2 >>> dis0 = test0.keyword(‘a‘,‘b‘,(‘c‘,‘d‘,‘c0‘,‘c1‘,‘d0‘,‘d1‘),e=‘e‘,f=‘f‘,g=‘g‘,h=‘h‘)3 a is  a4 b is  b5 non_keyword ((‘c‘, ‘d‘, ‘c0‘, ‘c1‘, ‘d0‘, ‘d1‘),)6 ‘h‘:h7 ‘e‘:e8 ‘f‘:f9 ‘g‘:g


所以可變長參數輸入具有一定的靈活性,更利用應對不同情境。

python可變長參數(非關鍵字及關鍵字參數)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.