The use of *args and **kwargs in Python functions to pass variable-length parameters

Source: Internet
Author: User

Reference from: http://www.jb51.net/article/78705.htm

The Single Form (*args) is used to pass a list of non-named key mutable parameters. The binary number form (**kwargs) is used to pass a variable parameter list of key values.

1. A fixed positional parameter and two variable-length parameters are passed.

def Test_var_args (farg, *args):  print"formal arg:", Farg  for in  args:    print"another arg:  ", Arg test_var_args ("A ", 31  3

2. A fixed parameter and two key-value parameters.

defTest_var_kwargs (Farg, * *Kwargs):Print "Formal ARG:", Farg forKeyinchKwargs:Print "Another keyword arg:%s:%s"%(Key, Kwargs[key]) Test_var_kwargs (Farg=1, myarg2=" Both", myarg3=3The result is: formal arg:1another keyword arg:myarg2:twoanother keyword arg:myarg3:3

3. When calling a function, use *args and **kwargs

defTest_var_args_call (arg1, Arg2, ARG3):Print "arg1:", Arg1Print "arg2:", Arg2Print "Arg3:", Arg3 args= (" Both", 3) Test_var_args_call (1, *args) The result is: arg1:1ARG2:TWOARG3:3-------------------------------------------Key-value pair mode:defTest_var_args_call (arg1, Arg2, ARG3):Print "arg1:", Arg1Print "arg2:", Arg2Print "Arg3:", Arg3 Kwargs= {"Arg3": 3,"arg2":" Both"}test_var_args_call (1, * *Kwargs) The result is: arg1:1ARG2:TWOARG3:3

The use of *args and **kwargs in Python functions to pass variable-length 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.