python-variable parameters and keyword parameters (*args **kw)

Source: Internet
Author: User

Objective:

Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.

Syntax for variable parameters and keyword parameters:

*args is a variable parameter, and args receives a tuple;

**KW is the keyword parameter, and kw receives a dict.

Using *args and **kw is a Python idiom, but it can also be used with other parameter names, but it's best to use idioms.

One, variable parameter *args

Definition: A variable parameter is the number of parameters passed in is variable, can be 0, 1, 2, ... A lot of.
Function: A parameter that can pass a lot of functions at once
Features: *args

We take the math titled example, given a set of numbers a,b...z, calculate sum = a * a + b * b + .... +z * Z

To define this function, we must determine the input parameters. Since the number of arguments is uncertain, we first think that a, b,..., Z can be passed in as a list or a tuple, so that the function can be defined as follows:

def cout(numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum

But when called, a list or tuple needs to be assembled first:
>>> cout([1, 2, 3])
14
>>> cout((1, 3, 5, 7))
84

If you take advantage of mutable parameters, the way you call a function can be simplified to this:
>>> cout(1, 2, 3)
14
>>> cout(1, 3, 5, 7)
84
So, let's change the parameter of the function to a variable parameter:

def cout(*numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum

When you define a mutable parameter and define a list or tuple parameter, you add an * number just before the parameter. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters:

>>> cout(1, 2)
5
>>> cout()
0
What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:
>>> nums = [1, 2, 3]
>>> cout(nums[0], nums[1], nums[2])
14
This kind of writing is of course feasible, the problem is too cumbersome, so python allows you to precede the list or tuple with an * number, the list or tuple of the elements into a variable parameter to pass in:

>>> nums = [1, 2, 3]
>>> calc(*nums)
14
*nums indicates that all elements of the list are nums as mutable parameters. This writing is quite useful and common.
----

Second, keyword parameter **kw

Definition: The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled into a dict inside the function. When you call a function, you can pass in only the required parameters.
Function: Functions of the extension function
Features: **kw

Take a look at the example:

def person(name, age, **kw):    print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)

The function person accepts the keyword parameter kw, in addition to the required parameter name and age. When you call this function, you can pass in only the required parameters:
>>> person(‘Michael‘, 30)
Name:michael age:30 Other: {}

You can also pass in any number of keyword parameters:
>>> person(‘Bob‘, 35, city=‘Beijing‘)
Name:bob age:35 Other: {' City ': ' Beijing '}

>>> person(‘Adam‘, 45, gender=‘M‘, job=‘Engineer‘)
Name:adam age:45 Other: {' Gender ': ' M ', ' job ': ' Engineer '}

What is the keyword argument for? It can extend the functionality of the function. For example, in the person function, we are guaranteed to receive both the name and the age parameters, but we can receive them if the caller is willing to provide more arguments. Imagine you are doing a user registration function, in addition to the user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.

Similar to variable parameters, you can also assemble a dict, and then convert the dict into a keyword parameter:

>>> extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
>>> person(‘Jack‘, 24, city=extra[‘city‘], job=extra[‘job‘])
Name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}

Of course, the above complex invocation can be simplified:
>>> extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
>>> person(‘Jack‘, 24, **extra)
Name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}

**extra that the extra this dict all key-value with the keyword parameters passed to the **kw parameter of the function, KW will get a dict, note that KW obtained dict is a copy of extra, the changes to KW will not affect the extra outside the function.

Above, the concept is clear ~ ~ Praise it?? ~ ~

python-variable parameters and keyword parameters (*args **kw)

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.