Use examples to illustrate Python's *args and **kwargs usage _python

Source: Internet
Author: User
Tags in python

Let's take a look at an example:

Copy Code code as follows:

>>> def foo (*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:
Copy Code code 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 from the examples above, these two are variable parameters in Python. *args represents any number of unnamed parameters, it is a tuple;**kwargs to represent the keyword parameter, it is a dict. When *args and **kwargs are used at the same time, the *args parameter columns must be called before **kwargs, such as foo (a=1, b= ' 2 ', c=3, a ', 1, None,), which prompts for syntax errors "SyntaxError: Non-keyword arg after keyword arg ". As shown:

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.