Python bit record 11: Collection of function parameters

Source: Internet
Author: User

In 8python, when you are unsure of the number of arguments to pass to a function, you can use *args and **kargs forms (args, Kargs can be defined with a different name).

I. Form of *args

EG1:

def func (x,*a): Print x print a func (1,2,3,4,5)

After calling the function, the result is:

1 (2, 3, 4, 5)

As can be seen from the results, when *a is used, when multiple arguments are passed to a function, the function passes the first argument to the first parameter, and then passes the remaining arguments to *a, and *a places the remaining arguments in a tuple.

If the function is defined (X,*A) and the argument is passed with only one argument, then *a will generate an empty tuple.

EG2:

def func (x,*a): Print x Print a func (1)

After calling the function, the result is:

1 ()

As you can see from the results, parameter 1 is passed to X, and *a generates an empty tuple.

It is important to note that when there is only one element in the element, the element needs to be appended with a ","

EG3:

def func (x,*a): Print x print a Func

After calling the function, the result is:

1 (2,)

There is only one element in the tuple, 2, followed by a ",".

Ii. Forms of *kargs

The *kargs form will have the received parameter in a dictionary, so it needs to be in the form of a key-value team when passing parameters.

EG1:

def func (i,**a): Print a print i func (3,x=4)

The result of the execution is:

{' X ': 4}3

Notice how the parameter is passed: x=4

Python bit record 11: Collection of function parameters

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.