is the parameter of a function a copy of the value passed, or a reference to memory?
Let's look at the following section of code:
A = []def fun (x): x.append (1) Fun (a) print (a)
Think about it: If you pass a copy of the value, then the list A should not change, or empty list, if you pass a reference, then a should be [1].
Execute the See output is [1], that is to prove that the function parameter passed is a reference.
However, look at the following code:
A = 1def fun (x): x = 2 return Xret = Fun (a) print (a) print (ret)
If, according to the above understanding, the function parameter passes a reference, then the value of a should be 2, but the output is 1, which is why?
Explain:
All variables in Python can be understood as "references" to an object in memory. What you need to remember here is that the type belongs to the object, not the variable. There are two types of objects, "mutable" and "non-changing" (immutable) objects. in Python, strings, tuples, and numbers are objects that cannot be changed , and list,dict are objects that can be modified. (This is the point of this question)
When a reference is passed to a function, the function automatically copies a reference, and the reference in the function does not have a semi-gross relationship with the outside reference. So in the second example, the function refers to an immutable object, and when the function returns, the outside reference does not change. The first example is different, and the reference in the function refers to a mutable object, and the operation is modified in memory as if it were a pointer address.
However, sometimes we do need to modify the global non-modifiable objects inside the function, what to do?
A = 1def fun (x): global a x = 2 a = ' Hello ' return Xret = Fun (a) print (a) print (ret)
Output:
Hello
2
We see through the keyword global that we have modified the value of a. However, we recommend minimizing the use of this method, because we modify the value of the global variable inside the function, and if there are other functions that use this variable, you might think that the value of a is 1, which results in an error and is not easy to troubleshoot.
Also: global variable conventions use uppercase letters.
Python's function parameter passing and global