Python function parameter type *, * * Difference _python

Source: Internet
Author: User
Tags closure mixed shallow copy stdin

Just beginning to learn Python,python is really much simpler and easier to use than Java. Memory recycling similar to the hotspot analysis of accessibility, immutable objects are also like the Java-type integer, with functions similar to the new version of C + + features, in general, easier to understand. Only part of the function of the "*" and "* *", closures and other issues, is really confusing, to understand the concept of writing down this document, but also hope this article can help other beginners.

So this article is a learning note, focusing on the use of the details and understanding, first of all the functions of the various parameter types in the invocation and declaration of the difference, and in the mix to pay attention to some of the details, and then talk about the closure of the relevant content. If there is something wrong, please correct me.

function argument without "*", "*" and "* *" difference
the key to understanding this problem is to distinguish between the 3 of the invocation and the declarative syntax.

function call Difference

1. A brief description of different types of parameters
#这里先说明python函数调用得语法为:

Copy Code code as follows:

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

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

Give an example to illustrate the difference between these 4 calling methods:
Copy Code code 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 Code code as follows:

A,b,c,d,e = X
Print A,b,c,d,e
#特别说明: X can also be a dict type, pass the key to the function when X is Dick type
>>> 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 details to be noted
then we explain the mixed use of different parameter types, to understand the different parameters of the mixed grammar needs to understand the following aspects.

First of all to understand that the function call use parameter types must be strictly in order, can not change the order, otherwise it will be an error. such as (a=1,2,3,4,5) will cause errors,; (*x,2,3) will also be considered illegal.

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

Finally, parameters are not allowed to be assigned multiple times.

For example, sequential Assignment (Positional_args) and list Assignment (*tuple_grp_nonkw_args) are logically related:

Copy Code code as follows:

#只有在顺序赋值, the list assignment exists in the result of the ROM sequence relationship
#正确的例子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 call last):
File "<stdin>", line 1, in <module>
Typeerror:test () got multiple values for keyword argument ' b '

#正确的例子1, processing is equivalent to
A,b = 1,2 #顺序参数
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多次赋值导致异常, only the sequential and list parameters exist.

function declaration Difference

Understanding the difference between different types of parameters in a function call, it is much simpler to understand the different parameters in a function declaration.

1. Description of parameter types in function declaration

There are only 3 types of function declarations, ARG, *ARG, **arg they have the exact opposite effect and function call. When invoked, *tuple_grp_nonkw_args converts the list to a sequential parameter, whereas the *ARG in the declaration converts the Order assignment (Positional_args) to a list. When invoked, **dict_grp_kw_args converts a dictionary to a keyword parameter, whereas **arg in the declaration converts the keyword parameter (keyword_args) to a dictionary.
Special reminder: *arg and **arg can be null values.

The following examples illustrate the above rules:

Copy Code code as follows:

#arg, examples of *arg and **ARG functions
def test2 (a,*b,**c):
Print A,b,c
#---------------------------
#*arg and **arg can not pass parameters
>>> test2 (1)
1 () {}
#arg必须传递参数
>>> test2 ()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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 processing
Print A,b,c

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


2. Processing order problem

Functions always process arg type parameters and then handle parameters for *arg and **arg types. Because *arg and **arg have different invocation parameter types, they do not have to be considered in order.

Copy 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 call last):
File "<stdin>", line 1, in <module>
Typeerror:test2 () got multiple values for keyword argument ' a '
#这里会报错得原因是, always deal with arg type parameters first
#该函数调用等价于
#处理arg类型参数:
A = 1
A = 1 #多次赋值, causing an exception
#处理其他类型参数
...
Print A,b,c

Closed Bag
Python functions, which can only access variables of two regions: 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 set so that a function can be executed outside of the area it is defined. This collection can be func_closure to get the collection of references. This is the same way that Python handles global variables, except that global variables store the reference collection in the __globals__ field. Func_closure is a tuple that stores the cell type, and each cell stores a context variable.

Also, the reason that the old version of Python's internal functions cannot be used in other scopes is not because each scoped variable is strictly isolated from the original scope, and the function loses the reference to the original context. It should be noted that the context information for the closure store is just as shallow copy, so the Mutable object passed to the internal function is still modified by other variables that have the reference to the object.

As an example:

Copy Code code as follows:

>>> def foo (x,y):
... def bar ():
... print x,y
... return bar
...
#查看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

#可变对象仍然能被修改
>>> 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.