Python function parameter type *, * * difference

Source: Internet
Author: User
Just beginning to learn Python,python is really much simpler and easier to use than Java. Memory recycling is similar to the accessibility analysis of the hotspot, immutable objects as well as Java's integer type, with functions similar to the new version of C + + features, overall understanding is relatively easy. Just the function part of the parameters of the "*" and "* *", closures and other issues, really confusing a, understand the concept after writing down this document, but also hope that this article can help other beginners.

So this article is a study note, focusing on the use of details and understanding, first of all, the function of the various parameter types in the invocation and declaration of the difference, and in the mix when the need to pay attention to some of the details, followed by the closure related content. If there is a wrong place, please correct me.

The function parameter does not have "*", "*" and "* *" difference
The key to understanding this problem is to separate the 3 differences in the invocation and declaration syntax.

function call Differences

1. Description of different types of parameters
#这里先说明python函数调用得语法为:
Copy the Code code as follows:


Func (Positional_args, Keyword_args,
*tuple_grp_nonkw_args, **dict_grp_kw_args)

#为了方便说明, then use the following function for example
def test (a,b,c,d,e):
Print A,b,c,d,e


Give an example of how these 4 calls differ:
Copy CodeThe code is as follows:


#-------------------------------
#positional_args方式
>>> Test (1,2,3,4,5)
1 2 3) 4 5

#这种调用方式的函数处理等价于
A,b,c,d,e = 1,2,3,4,5
Print A,b,c,d,e

#-------------------------------
#keyword_args方式
>>> Test (a=1,b=3,c=4,d=2,e=1)
1 3 4) 2 1

#这种处理方式得函数处理等价于
A=1
B=3
C=4
d=2
E=1
Print A,b,c,d,e

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


#这种方式函数处理等价于
Copy CodeThe code is as follows:


A,b,c,d,e = X
Print A,b,c,d,e
#特别说明: X can also be dict type, X is Dick type when key is passed to function
>>> y
{' A ': 1, ' C ': 6, ' B ': 2, ' E ': 1, ' d ': 1}
>>> Test (*y)
A C b e D

#---------------------------------
#**dict_grp_kw_args Way
>>> y
{' A ': 1, ' C ': 6, ' B ': 2, ' E ': 1, ' d ': 1}
>>> Test (**y)
1 2 6) 1 1

#这种函数处理方式等价于
A = Y[' a ']
b = y[' B ']
... #c, d,e no longer repeat
Print A,b,c,d,e

2. Different types of parameters mixed with some of the details to be noted
The following is a description of the mixed use of different parameter types, in order to understand the different parameters mixed with the syntax needs to understand these aspects.

The first thing to understand is that function calls using parameter types must be in strict order, can not be arbitrarily reversed order, otherwise it will error. such as (a=1,2,3,4,5) will cause an error,; (*x,2,3) will also be considered illegal.

Second, the order in which the functions are processed in different ways is also in accordance with the order of the types described above. Because the #keyword_args mode and **dict_grp_kw_args mode are specified for parameter one by one, there is no order. So you just need to consider order assignment (Positional_args) and the order of the list assignment (*tuple_grp_nonkw_args). Therefore, it can be simply understood that only the #positional_args way, the #*tuple_grp_nonkw_args way has the logical order.

Finally, the parameter is not allowed to be assigned multiple times.

For example, sequential Assignment (Positional_args) and list assignment (*tuple_grp_nonkw_args) have a logical succession relationship:
Copy the Code code as follows:


#只有在顺序赋值, the list assignment has a compilation relationship on the result.
#正确的例子1
>>> x = {3,4,5}
>>> Test (1,2,*X)
1 2 3) 4 5
#正确的例子2
>>> Test (1,E=2,*X)
1 3 4) 5 2

#错误的例子
>>> Test (1,B=2,*X)
Traceback (most recent):
File " ", line 1, in
Typeerror:test () got multiple values for keyword argument ' b '

#正确的例子1, processing is equivalent to
A, B = #顺序参数
C,d,e = x #列表参数
Print A,b,c,d,e

#正确的例子2, processing is equivalent to
A = 1 #顺序参数
E = 2 #关键字参数
B,c,d = x #列表参数

#错误的例子, processing is equivalent to
A = 1 #顺序参数
b = 2 #关键字参数
B,c,d = x #列表参数
#这里由于b多次赋值导致异常, it can be seen that there are only sequence parameters and list parameters that have a compilation relationship.

function declaration Differences

After understanding the difference between different types of parameters in a function call, it is much easier to understand the difference between the different parameters in a function declaration.

1. Description of parameter types in function declarations

There are only 3 types of function declarations, ARG, *ARG, **arg they have effects and function calls are just the opposite. When called, *tuple_grp_nonkw_args converts the list to a sequential parameter, while the *ARG in the declaration is the function of converting the order assignment (Positional_args) to a list. Called when **dict_grp_kw_args converts a dictionary to a keyword argument, whereas **arg in the declaration translates the keyword argument (keyword_args) into a dictionary.
Special reminder: *arg and **arg can be null values.

The following examples illustrate the above rules:
Copy the Code code as follows:


#arg, examples of *arg and **arg effects
def test2 (a,*b,**c):
Print A,b,c
#---------------------------
#*arg and **arg can not pass parameters
>>> test2 (1)
1 () {}
#arg必须传递参数
>>> test2 ()
Traceback (most recent):
File " ", line 1, in
Typeerror:test2 () takes at least 1 argument (0 given)

#----------------------------
#*arg convert shun Positional_args to list
>>> test2 (1,2,[1,2],{' a ': 1, ' B ': 2})
1 (2, [1, 2], {' A ': 1, ' B ': 2}) {}
#该处理等价于
A = 1 #arg参数处理
b = 2,[1,2],{' A ': 1, ' B ': 2} #*arg parameter handling
c = dict () #**arg parameter handling
Print A,b,c

#-----------------------------
#**arg converting Keyword_args to a dictionary
>>> test2 (1,2,3,d={1:2,3:4}, c=12, b=1)
1 (2, 3) {' C ': ' B ': 1, ' d ': {1:2, 3:4}}
#该处理等价于
A = 1 #arg参数处理
b= 2,3 #*arg parameter processing
#**arg parameter handling
c = Dict ()
c[' d '] = {1:2, 3:4}
C[' C '] = 12
C[' B '] = 1
Print A,b,c


2. Handling Order Issues

The function always processes the arg type parameter before processing the parameters of the *arg and **arg types. Because *arg and **arg have different invocation parameter types, they do not need to be considered in their order.
Copy the Code code as follows:


def test2 (a,*b,**c):
Print A,b,c
>>> test2 (1, b=[1,2,3], C={1:2, 3:4},a=1)
Traceback (most recent):
File " ", line 1, in
Typeerror:test2 () got multiple values for keyword argument ' a '
#这里会报错得原因是, the parameters of the ARG type are always processed first
#该函数调用等价于
#处理arg类型参数:
A = 1
A = 1 #多次赋值, causing an exception
#处理其他类型参数
...
Print A,b,c


Closed Package
Python's function, which originally had access to only two variables of the region: Global, and local (function context). In fact, the function itself is also an object and has its own scope. A closure is a combination of a function and a reference collection that allows a function to execute outside of the area it is defined in. This collection can be obtained by func_closure to this reference collection. This is the same way that Python handles global variables, except that global variables store reference collections in the __globals__ field. Func_closure is a tuple that stores a cell type, and each cell stores a context variable.

In addition, the old version of Python's intrinsic function cannot be used in other scopes, not because the variables of each scope are strictly isolated from each other, but instead are separated from the original scope, the function loses its original context reference. It is important to note that the context information of the closure store is the same as the shallow copy, so the Mutable object passed to the intrinsic function will still be modified by other variables that have the reference to the object.

As an example:
Copy the Code code as follows:


>>> def foo (x, y):
... def bar ():
.. print x, y
... return bar
...
#查看func_closure的引用信息
>>> a = [+]
>>> B = foo (a,0)
>>> b.func_closure[0].cell_contents
[1, 2]
>>> b.func_closure[1].cell_contents
0
>>> B ()
[1, 2] 0

#可变对象仍然能被修改
>>> A.append (3)
>>> b.func_closure[0].cell_contents
[1, 2, 3]
>>> B ()
[1, 2, 3] 0

  • 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.