Python tips: what are * args and ** kwargs?

Source: Internet
Author: User

Let's look at an example:

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 result is 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 variable parameters in python. * Args indicates any number of unnamed parameters. It is a tuple. ** kwargs indicates a keyword parameter, which is a dict. When both * args and ** kwargs are used, the * args parameter column must be before ** kwargs, such as foo (a = 1, B = '2', c = 3, if you call this method, a syntax error "SyntaxError: non-keyword arg after keyword arg" is displayed ".

 

You know what * args and ** kwargs are. Another nice usage is to create a dictionary:

    def kw_dict(**kwargs):        return kwargs    print kw_dict(a=1,b=2,c=3) == {'a':1, 'b':2, 'c':3}

In fact, python has a dict class. You can use dict (a = 1, B = 2, c = 3) to create a dictionary.

 

"My life is short. I use python ."

Technorati labels: python, tuple, dict, * args, ** kwargs

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.