Python可變參數函數的實現

來源:互聯網
上載者:User

同C語言一樣,Python中也有可變參數函數,即一個函數可以接收多個參數,而這些參數的個數在函數調用之前事先是不知道的。

在C裡面最典型的例子就是printf函數,同樣在python裡面使用可變參數也可以很方便的實現printf()

代碼如下:

def printf(fmt, *arg):    print fmt % arg

printf定義中的*arg就是可變參數,它的類型為tuple,代表了除fmt參數之外的所有傳入參數。

但如果我們傳入的可變參數是字典,那麼*arg的定義就不夠用了,這時我們應該使用**arg來定義函數。

這時我們調用函數的方式變為:

定義:def fun(**arg)

fun(key1 = val1, key2=val2, ...)

如: fun(One=1, Two=2)

代碼如下:

def testFun1(**arg):    for k in arg.keys():        printf("arg[%s] = %s.", k, arg[k])def testFun2(*arg1, **arg2):    print arg1    print arg2if __name__ == '__main__':    printf("How do you do? %d, %d", 2, 3)     testFun1(One=1, Two=2)    testFun2(1, 2, 3, One=1, Two=2, Three=3)

輸出結果:

How do you do? 2, 3
arg[Two] = 2.
arg[One] = 1.
(1, 2, 3)
{'Three': 3, 'Two': 2, 'One': 1}

聯繫我們

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