python-function (ii)

Source: Internet
Author: User

Functions in Python (ii)

In the previous article, we mentioned the definition and use of functions in Python, and in this article we discuss some of the deeper topics about functions. In the study of C-language functions, the problems encountered are mainly the difference of tangible parameters, the transfer and change of parameters, and the scope of variables. Also in Python, there are problems with the understanding and use of functions. Let's go through the following.

I. The difference between a function parameter and an argument
Formal parameter names are formal parameters, and variable names in parentheses after the function name are used as formal parameters when defining a function with the DEF keyword.
The arguments are all called actual parameters, and the values provided when the function is called or variables are called as actual arguments.

As an example:

def add (A, b):      //A and B here is the formal    parameter  return A +Badd (1,2)     //the 1 and 2 here are arguments
X=2y=3Add (x, y) //This is an argument

Two. Transfer and change of parameters
  Let's look at the "passing of function parameters" question in Python.

First of all, before we discuss this, we need to make it clear that everything in Python is object, and that the variable holds the object's reference. This is a bit hard to understand, "everything is the object"? Yes, that's true in Python, including the string constants we used to use, integer constants are objects. If you don't believe it, you can verify it:

Example 1,

Print ID (2)
x=2Print ID (x)

Y='hello'print id (y)

As you can see from the results, the values for ID (2) and ID (x) are the same, and the values for ID (' hello ') and ID (y) are the same.
In Python everything is object, like 2, ' Hello ' is an object, but 2 is an integer object, and ' Hello ' is a string object.
Above the x=2, the actual process in Python is this: first apply for a memory allocation to an integer object to store an integer value of 2, and then let the variable x point to the object, is actually pointing to this memory (here is a bit similar to the C language pointer). As with the result of ID (2) and ID (x), the description ID function returns the address of the object to which the variable is directed when it is acting on the variable. Because the variable is also an object, you can consider x as a reference to object 2 here.

Example 2,

x=2Print ID (x)
Y=2print ID (y)
s='hello'print ID (s) t=Sprint ID (t)


 
from the run result you can see that the result of ID (x) and ID (y) is the same, and the result of ID (s) and ID (t) is the same. This means that x and Y point to the same object, and T and S are also pointing to the same object. x=2 This sentence makes the variable x point to Object 2 of type int, and y=2 This sentence does not re-allocate space for 2, but instead makes Y point directly to Object 2 of the already existing int type. This is very well understood, because in itself just want to assign a value of 2, and in memory already exists such an int type Object 2, so that the direct Y point to the existing object. This will not only achieve the goal, but also save memory space. T=s This variable is assigned to each other, is also equivalent to let T point to the existing string type of the object ' hello ' (this principle and C language pointer in the reciprocal assignment of a bit similar).

look at this picture to understand:


Example 3,

 x=2  print ID ( 2  ) Print ID (x) 
x =3 print ID ( 3 ) Print ID (x)
L =[1 , 2 , 3 ]m =lprint ID (L) Print ID (M) Print ID (l[ 2 l[ Span style= "COLOR: #800080" >0 ]=2 print ID ( L) Print M

The result of the operation is:

The following analysis of the results, two times the ID (x) value is different, this may be a bit difficult to understand. Note that in Python, objects of a single element are not allowed to change, such as Integer data, strings, floating-point numbers, and so on. x=3 The execution of this sentence is not to get the address of the object originally pointed to X, and then change the value in memory to 3, but the new request for a memory to store object 3, and then x to point to Object 3, so the value of two times ID (x) is different. However, after changing the value of one of the child elements in L, the value of ID (l) has not changed. in Python, objects of complex elements are allowed to change, such as lists, dictionaries, tuples, and so on. A variable in Python stores a reference to an object, and for a list, its ID () value returns the storage address of the first child element of the list l[0]. as in the example above, l=[1,2,3], where L has three sub-elements l[0],l[1],l[2],l[0], l[1], l[2] respectively to the object 1, 2, 3,id (L) value and the storage address of object 3 is the same, see the following diagram to understand:

Because L and M point to the same object, after changing the value of the L neutron element, m also changes, but the ID (l) value does not change, because the l[0]=2 just let l[0] point to Object 2 again, and L[0] itself has not changed the storage address, so ID (L) The value is not changed (the value of ID (L) is actually equal to the storage address of l[0] itself). As follows:

Here's a discussion of "parameter passing and changing of functions".
Parameter passing in Python takes a value pass, which is a bit like the C language.

Example 1,

 def modify1 (m,k): M  =2   K  =[4 , 5 , 6  ]  return  Span style= "COLOR: #000000" > def modify2 (m,k): M  =2   k[ 0 ]=0  return  n  =100  l  =[1 , 2 , 3  ] 
Modify1 (n,l) print nprint L
modify2 (n,l) print Nprint L

The result of the program operation is:

As can be seen from the results, N and l have not changed since the execution of Modify1 (), and N has not changed since the execution of Modify2 (), and L has changed. Because parameter passing in Python takes a value-passing method, the ID () values of N and L are obtained first, and then the parameters m and k are allocated space, and the M and K points to object 100 and object [three-way], respectively, when the function modify1 is executed. m=2 this sentence to re-point m to object 2, and k=[4,5,6] This sentence let K again point to the object [4,5,6]. This change does not affect the arguments N and L, so there is no change in N and L after the execution of the modify1, and when the function modify2 is executed, the same way that M and K points to object 2 and object [three-way], but K[0]=0 lets K[0] Re-pointing to object 0 (note that K and L point to the same memory), so any changes to the memory data that K points to will also affect L, so after executing Modify2, L changed.



Three. Scope of variables
In Python, there is also the problem of scopes. in Python, a symbol table is generated for each hierarchy, the inside of which can invoke variables in the outer layer, and the outer layers cannot call the variables in the inner layer, and when the outer and inner variables are the same name, the outer variables are masked by the inner variables.
As an example:

def function ():    x=2    count=2while     count>0 :        x=3        print x        count=count-1
function ()

In function functions, there is a variable x outside the while loop, and the variable x outside the while loop is masked out. Note that variable scopes defined inside a function are limited to the inside of the function and cannot be called outside the function, which is generally called a local variable.

There is also a variable called a global variable, which is defined outside the function and scoped to the entire file. Global variables can be applied directly inside a function, but if you want to change global variables inside a function, you must declare them using the Global keyword.

x=2def fun1 ():    print x    def fun2 ():    Global  x    x=3     print xfun1 () fun2 () print x



python-function (ii)

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.