Python mutable parameters * and * *

Source: Internet
Author: User

Variable parameters

In the Python function, you can also define mutable parameters. As the name implies, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.

We take the math titled example, given a set of numbers a,b,c ..., please calculate a2 + b2 + C2 + ....

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

def calc(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:

>>> calc([1, 2, 3])14>>> calc((1, 3, 5, 7))84

If you take advantage of mutable parameters, the way you call a function can be simplified to this:

>>> calc(1, 2, 3)14>>> calc(1, 3, 5, 7)84

So, let's change the parameter of the function to a variable parameter:

def calc(*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, just precede the parameter with a * number. 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:

>>> calc(1, 2)5>>> calc()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]>>> calc(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 add a number in front of a list or a tuple * , the elements of a list or a tuple into a mutable parameter to pass in:

>>> nums = [1, 2, 3]>>> calc(*nums)14

*nums indicates that nums all elements of this list are passed in as mutable parameters . This writing is quite useful and common.

Keyword parameters

Variable parameters allow you to pass in 0 or any of the parameters that are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict. Take a look at the example:

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

person name age The function accepts the keyword parameter in addition to the required parameters kw . 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 a person function, we are guaranteed to receive name and both age parameters, but if the caller is willing to provide more arguments, we can receive them. 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‘}

**extraIt means that extra all the key-value of this dict are passed to the function parameter with the keyword argument **kw , and kw a dict is obtained, the kw dict is a extra copy, and the kw change does not affect the outside of the function extra .

Python mutable parameters * and * *

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.