function of the default parameter of the large pit, the parameter of the variable parameter __ function

Source: Internet
Author: User
Tags function definition

Transferred from Liaoche's official website:

The default parameters are useful, but improper use can also fall into the pit. The default parameter has a maximum pit: The value of the default parameter may change unconsciously in the process of calling the function multiple times, which is very different from C + +.

The demo is as follows:

def add_end (l=[]):
    l.append (' End ') return
    L

When you call normally, the result seems to be good:

>>> Add_end ([1, 2, 3])
[1, 2, 3, ' end ']
>>> add_end ([' X ', ' y ', ' z '])
[' x ', ' y ', ' z '], ' end ']
When you use the default parameter invocation, the first result is also true:

>>> add_end ()
[' End ']
However, when you invoke Add_end () again, the result is incorrect:

>>> add_end ()
["End", "End"]
>>> add_end () ["End", "End", "End"
]

Explanations for the reasons are as follows:
When the Python function is defined, the value of the default parameter L is computed. That is [], because the default parameter L is also a variable, it points to the object [], each time the function is called, if the contents of L are changed, the contents of the default parameter will be changed at the next call, no longer the [] of the function definition.

Therefore, remember that the default parameters must not be defined as mutable objects, and the list is a mutable object. Otherwise, the default parameters may be silently changed during the function call.

the benefit of the Python invariant object: Because once the invariant object is created, the data inside the object cannot be modified, thus reducing the error caused by the modification of the data. In addition, because the object is invariant, the multitasking environment reads the object without the need for locking, while reading the problem is not. When we write a program, if we can design a invariant object, then try to design unchanged objects.


variable parameters in Python functions, you can also define variable parameters. As the name suggests, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0. (in C + +, is the pass pointer)

Def calc (*numbers):
    sum = 0 for
    n in numbers:
        sum = SUM + N * n * return
    sum
To define a variable parameter and define a list or tuple parameter, just add a * number in front of the parameter (* is not related to the pointer, not the category, the parameter preceded by * only represents, number is a variable 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 of the arguments, including 0 parameters:
>>> Calc (1, 2)
5
>>> calc ()
0
variable parameters allow you to pass in 0 or any of the parameters, which are automatically assembled as a tuple when the function is called.

Keyword parameter: keyword parameter allows you to pass in 0 or any containing Name of parameterOf ParametersThese keyword parameters are automatically assembled within a function as a dict:dict format is {parameter name: parameter}
def person (name, age, **kw):
    print (' name: ', Name, ' Age: ', age, ' other: ', kw)
Keyword parameter kw, when you call the function, you can pass in only the required parameters
>>> person (' Michael, "
Name:michael age:30 other: {}
You can also pass in any number of keyword parameters:
>>> person (' Bob ', "city= ' Beijing ')
name:bob age:35 Other: {" City ": ' Beijing '}
>>> person ( ' Adam ', gender= ' m ', job= ' Engineer ')
Name:adam age:45 Other: {' Gender ': ' m ', ' job ': ' Engineer '}

Similar to a variable parameter, you can also assemble a dict and then convert the dict to a keyword parameter.
>>> extra = {' City ': ' Beijing ', ' job ': ' Engineer '}
>>> person (' Jack ', **extra)
Name:jack A Ge:24: {' City ': ' Beijing ', ' job ': ' Engineer '}
**extra said that extra this dict all key-value with keyword parameters passed to the function of the **kw parameter, KW will get a dict, note kw dict is a copy of the extra, the changes to KW will not affect the function of the extra 。

Summary: 1, the default parameters must be used with mutable objects, if it is a mutable object, the program may run with logic errors 2, *args is a variable parameter, args receives is a tuple 3, **kw is the keyword parameter, kw receives is a dict


















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.