Implementation of Python variable parameter function

Source: Internet
Author: User
Tags in python

As with C, there are variable parameter functions in Python, where a function can receive multiple parameters that are not known in advance of the function call.

The most typical example in C is the printf function, which also makes it easy to implement printf using variable parameters in Python ()

The code is as follows:

def printf (FMT, *arg):
    print FMT% arg

The *arg in the printf definition is the variable parameter, which is of type tuple, representing all incoming arguments except the FMT parameter.

But if the variable argument we pass in is a dictionary, then the definition of *arg is not enough, and then we should use **arg to define the function.

Then the way we call the function becomes:

Definition: def fun (**arg)

Fun (Key1 = Val1, Key2=val2, ...)

such as: Fun (one=1, two=2)

The code is as follows:

def testFun1 (**arg):
    for K in Arg.keys ():
        printf ("arg[%s" =%s. ", K, Arg[k])

def testFun2 (*arg1, **arg2): 
 print arg1
    Print arg2

if __name__ = = ' __main__ ':
    printf ("How Do"? %d,%d ", 2, 3) 
    testFun1 (one=1, two=2)
    testFun2 (1, 2, 3, one=1, two=2, three=3)

Output results:

How do I do? 2, 3
Arg[two] = 2.
Arg[one] = 1.
(1, 2, 3)
{' Three ': 3, ' two ': 2, ' One ': 1}

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.