A detailed description of Python's *args and **kwargs

Source: Internet
Author: User
*args represents any number of nameless arguments, which is a tuple;**kwargs representing the keyword argument, which is a dict.

def fun (*args, **kwargs):    print ' args = ', args    print ' Kwargs = ', Kwargs    print ' # # # ' If __name__ = = ' __main__ ' :    foo (1,2,3,4)    foo (a=1,b=2,c=3) foo (    1,2,3,4, a=1,b=2,c=3)    foo (' A ', 1, None, a=1, b= ' 2 ', c=3)

The output results are as follows:

args =  (1, 2, 3, 4) Kwargs =  {} # # #args =  () Kwargs =  {' A ': 1, ' C ': 3, ' B ': 2} # # #args =  (1, 2, 3, 4 ) Kwargs =  {' A ': 1, ' C ': 3, ' B ': 2} # # #args =  (' A ', 1, None) Kwargs =  {' A ': 1, ' C ': 3, ' B ': ' 2 '} # # #

As you can see, these two are mutable parameters in Python.

Note: When using both *args and **kwargs, the parameter column must be *args before **kwargs, such as foo (a=1, b= ' 2 ', c=3, a ', 1, None,) and will prompt syntax error "SyntaxError: Non-keyword arg after keyword arg ".

def fun2 (param1, *args, **kwargs):    print ' param1 = ', param1    print ' args = ', args    print ' Kwargs = ', kwargs
  print ' # # # ' fun2 (1, 2, 3, 4, a=1,b=2,c=3)

Output Result:

param1 =  1args =  (2,3,4) Kwargs =  {' A ': 1, ' C ': 3, ' B ': 2} # # #

1 assigned to the param1, the rest of the 2,3,4 to *args, the others are assigned to the **kwargs

There is also a very nice way to create a dictionary:

def kw_dict (**kwargs):    return kwargsprint kw_dict (a=1,b=2,c=3)

Results:

{' A ': 1, ' B ': 2, ' C ': 3}

In fact Python has the Dict class, you can use Dict (a=1,b=2,c=3) to create a dictionary.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.