Python function parameter type *, ** difference, python Function

Source: Internet
Author: User

Python function parameter type *, ** difference, python Function

At the beginning, python was much simpler and easier to use than java. Memory collection is similar to the Accessibility Analysis of hot spot, and the immutable object is also of the Integer type in java. The with function is similar to the features of the new C ++ version. In general, it is easier to understand. It's just a confusing question about "*" and "**", closures, and other parameters of the function. After figuring out the concept, write down this article, and hope this article can help other beginners.

Therefore, this article is a learning note, focusing on the details and understanding of the use. First, we will introduce the differences between various function parameter types in call and description, and some of the details that need to be paid attention to when using the plug-in. Later, we talked about the closure-related content. If something is wrong, please correct it.

Function parameters do not include "*", "*", or "**".
The key to understanding this problem lies in the difference between the three operators in the call and declaration syntax.

Differences between function calls

1. Brief descriptions of parameters of different types
# The python function call syntax is as follows:
Copy codeThe Code is as follows:
Func (positional_args, keyword_args,
* Tuple_grp_nonkw_args, ** dict_grp_kw_args)
 
# For convenience, use the following functions for example.
Def test (a, B, c, d, e ):
Print a, B, c, d, e

Here is an example to illustrate the differences between the four call methods:
Copy codeThe Code is as follows:
#-------------------------------
# Positional_args Mode
>>> Test (1, 2, 3, 4, 5)
1 2 3 4 5

# Function processing in this call method is equivalent
A, B, c, d, e = 1, 2, 3, 4, 5
Print a, B, c, d, e

#-------------------------------
# Keyword_args Method
>>> Test (a = 1, B = 3, c = 4, d = 2, e = 1)
1 3 4 2 1

# Function processing in this way is equivalent
A = 1
B = 3
C = 4
D = 2
E = 1
Print a, B, c, d, e

#-------------------------------
# * Tuple_grp_nonkw_args Mode
>>> X = 1, 2, 4, 5
>>> Test (* x)
1 2 3 4 5

# Function processing in this way is equivalent
Copy codeThe Code is as follows:
A, B, c, d, e = x
Print a, B, c, d, e
# Note: x can also be of the dict type. If x is of the dick type, the key is passed to the function.
>>> Y
{'A': 1, 'C': 6, 'B': 2, 'E': 1, 'D': 1}
>>> Test (* y)
A c B e d

#---------------------------------
# ** Dict_grp_kw_args Method
>>> Y
{'A': 1, 'C': 6, 'B': 2, 'E': 1, 'D': 1}
>>> Test (** y)
1 2 6 1 1

# This function processing method is equivalent
A = y ['a']
B = y ['B']
... # C, d, e
Print a, B, c, d, e

2. Notes for mixing different types of parameters
Next we will describe the mixed use of different parameter types. To understand the syntax of mixed parameters, we need to understand the following aspects.

First of all, you must understand that the type of parameters used for function calls must be strictly in order and cannot change the order at will. Otherwise, an error is reported. for example, (a =, 5) will cause an error, and (* x, 2, 3) will also be treated as invalid.

Secondly, the order in which the function processes different methods is also in the order described above. because the # keyword_args method and the ** dict_grp_kw_args method specify parameters one by one, there is no order. therefore, you only need to consider the order of order assignment (positional_args) and list assignment (* tuple_grp_nonkw_args. therefore, it can be simply understood that only the # positional_args mode and the # * tuple_grp_nonkw_args mode have a logical order.

Finally, parameters cannot be assigned multiple times.

For example, the logical sequence of order assignment (positional_args) and list assignment (* tuple_grp_nonkw_args) is as follows:
Copy codeThe Code is as follows:
# Only values are assigned in order, and the List Value assignment result has a series of records.
# Example 1
>>> X = {3, 4, 5}
>>> Test (1, 2, * x)
1 2 3 4 5
# Example 2
>>> Test (1, e = 2, * x)
1 3 4 5 2

# Incorrect example
>>> Test (1, B = 2, * x)
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
TypeError: test () got multiple values for keyword argument 'B'

# Correct example 1. Processing is equivalent
A, B = 1, 2 # sequential Parameters
C, d, e = x # LIST Parameters
Print a, B, c, d, e

# Correct example 2. Processing is equivalent
A = 1 # sequence Parameters
E = 2 # keyword Parameters
B, c, d = x # LIST Parameters

# Example of an error. Processing is equivalent
A = 1 # sequence Parameters
B = 2 # keyword Parameters
B, c, d = x # LIST Parameters
# Here, the error is caused by multiple assignments of B. It can be seen that only sequence parameters and list parameters have a series of sequential relationships.

Differences in function declaration

After understanding the differences between different types of parameters in function calls, it is much easier to understand the differences between different parameters in function declaration.

1. parameter types in function declaration

Function declaration has only three types: arg, * arg, and ** arg. They have the opposite effect of function calling. during the call, * tuple_grp_nonkw_args converts the list to an ordered parameter, and * arg in the Declaration converts the ordered value (positional_args) to a list. during the call, ** dict_grp_kw_args converts the dictionary to a keyword parameter, while ** arg in the Declaration converts the keyword parameter (keyword_args) to a dictionary.
Note: * arg and ** arg can be null.

The following are examples of the above rules:
Copy codeThe Code is as follows:
# Arg, * arg, and ** arg examples
Def test2 (a, * B, ** c ):
Print a, B, c
#---------------------------
# * Arg and ** arg do not pass Parameters
>>> Test2 (1)
1 (){}
# Parameters must be passed in arg
>>> Test2 ()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
TypeError: test2 () takes at least 1 argument (0 given)

#----------------------------
# * Arg converts positional_args to a list
>>> Test2 (1, 2, [1, 2], {'A': 1, 'B': 2 })
1 (2, [1, 2], {'A': 1, 'B': 2 }){}
# This processing is equivalent
A = 1 # arg parameter Processing
B = 2, [1, 2], {'A': 1, 'B': 2} # * arg parameter Processing
C = dict () # ** arg parameter Processing
Print a, B, c

#-----------------------------
# ** Arg converts keyword_args to a dictionary
>>> Test2 (, 3, d = {,}, c = 12, B = 1)
1 (2, 3) {'C': 12, 'B': 1, 'D': {1: 2, 3: 4 }}
# This processing is equivalent
A = 1 # arg parameter Processing
B = 2, 3 # * arg parameter Processing
# ** Arg parameter Processing
C = dict ()
C ['D'] =}
C ['C'] = 12
C ['B'] = 1
Print a, B, c

2. Handling order problems

The function always processes parameters of the arg type before * arg and ** arg. because * arg and ** arg have different types of call parameters, their order is not required.
Copy codeThe Code is as follows:
Def test2 (a, * B, ** c ):
Print a, B, c
>>> Test2 (1, B = [, 3], c = {,}, a = 1)
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
TypeError: test2 () got multiple values for keyword argument 'A'
# Here, an error is reported because parameters of the arg type are always processed first.
# This function call is equivalent
# Processing arg parameters:
A = 1
A = 1 # multiple assignments, resulting in exceptions
# Processing other types of parameters
...
Print a, B, c

Closure
Python functions can only access the variables in two regions: global and local (function context ). in fact, a function itself is also an object and has its own scope. through the combination of a function and a reference set, a closure allows a function to be executed outside the defined area. this set can be obtained through func_closure. this is the same as how python processes global variables, except that the reference set of global variables is stored in the _ globals _ field. func_closure is a cell-type tuples. Each cell stores a context variable.

In addition, the reason why the old version of python's internal functions cannot be used in other scopes is not that the variables in each scope are strictly isolated from each other, but that, after the original scope, the function has no reference to the original context. It should be noted that the context information stored in the closure is also a small copy, so the variable objects passed to the internal function will still be modified by other variables that have referenced this object.

For example:
Copy codeThe Code is as follows:
>>> Def foo (x, y ):
... Def bar ():
... Print x, y
... Return bar
...
# Viewing reference information of func_closure
>>> A = [1, 2]
>>> B = foo (a, 0)
>>> B. func_closure [0]. cell_contents
[1, 2]
>>> B. func_closure [1]. cell_contents
0
>>> B ()
[1, 2] 0

# Variable objects can still be modified
>>> A. append (3)
>>> B. func_closure [0]. cell_contents
[1, 2, 3]
>>> B ()
[1, 2, 3] 0

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.