How Python uses *arg and **kwargs__python

Source: Internet
Author: User

This particular definition of *arg and *kwargs in a function is used to pass an indefinite number of arguments to a function. *arg (Only one *) is used to pass the list array, while **kwargs (two *) is used to pass the Dict dictionary

def Test_var_args (Farg, *args):
    print "formal arg:", Farg for
    arg in args:
        print "Another arg:", arg

test _var_args (1, "two", 3)
# Results:
formal arg:1
another arg:two another arg:3
def Test_var_kwargs (Farg, **kwargs):
    print "formal arg:", Farg for
    key in Kwargs:
        print "Another keyword arg: %s:%s "% (key, Kwargs[key])

Test_var_kwargs (farg=1, myarg2=" two ", myarg3=3)
# Results:
formal arg:1
another keyword arg:myarg2:two another keyword
use *arg and **kwargs when calling functions
def test_var_args_call (Arg1, Arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "Arg3:", Arg3

args = ("Two", 3)
Test_var_args_call (1, *args)
# Results:
arg1:1
arg2:two
arg3:3
def test_var_args_call (Arg1, Arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "Arg3:", Arg3

Kwargs = {"Arg3": 3, "arg2": "Two"}
Test_var_args_call (1, **kwargs)
# Results:
arg1:1
arg2:two
arg3:3
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.