How to use *args and **kwargs in Python

來源:互聯網
上載者:User

標籤:os   io   for   ar   cti   div   amp   python   

Or, How to use variable length argument lists in Python.

The special syntax, *args and **kwargs in function definitions is used to pass a variable number of arguments to a function. The single asterisk form (*args) is used to pass a non-keyworded, variable-length argument list, and the double asterisk form is used to pass a keyworded, variable-length argument list. Here is an example of how to use the non-keyworded form. This example passes one formal (positional) argument, and two more variable length arguments.

def test_var_args(farg, *args):    print "formal arg:", farg    for arg in args:        print "another arg:", argtest_var_args(1, "two", 3)

Results:

formal arg: 1another arg: twoanother arg: 3

 

Here is an example of how to use the keyworded form. Again, one formal argument and two keyworded variable arguments are passed.

def test_var_kwargs(farg, **kwargs):    print "formal arg:", farg    for key in kwargs:        print "another keyword arg: %s: %s" % (key, kwargs[key])test_var_kwargs(farg=1, myarg2="two", myarg3=3)

Results:

formal arg: 1another keyword arg: myarg2: twoanother keyword arg: myarg3: 3

 

Using  *args and  **kwargs when  calling a function

This special syntax can be used, not only in function definitions, but also whencalling a function.

def test_var_args_call(arg1, arg2, arg3):    print "arg1:", arg1    print "arg2:", arg2    print "arg3:", arg3args = ("two", 3)test_var_args_call(1, *args)

 

Results:

arg1: 1arg2: twoarg3: 3

Here is an example using the keyworded form when calling a function:

def test_var_args_call(arg1, arg2, arg3):    print "arg1:", arg1    print "arg2:", arg2    print "arg3:", arg3kwargs = {"arg3": 3, "arg2": "two"}test_var_args_call(1, **kwargs)

Results:

arg1: 1arg2: twoarg3: 3
相關文章

聯繫我們

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