Python basic introductory tutorial: passing parameters by value or by reference

Before that, let’s take a look at the relationship between variables and objects: everything in Python is an object, a number is an object, a list is an object, a function is an object, everything vb.net tutorial
is an object. The variable is a reference (also called a name or label) of an object, and the operations of the object are all done by reference. For example, a = [] is an empty list c# tutorial object, and the variable a is a reference to this object.
Example 1

def test(c):
 c.append("hello world")
 print(c,id(c))
 return
list = [1,2]
test(list)
print(list,id(list))

Output

[1, 2,'hello world'] 2463790879240
[1, 2,'hello world'] 2463790879240
Before executing the test function, both the list and the parameter c point to the same object. When the test is executed, there is no reassignment or new value. In the pointing process, the append method just inserts an element into the list object, the object is still the original object, but the content in the object has changed, because the parameter c and the list list are bound to the same object, execute c.append and list. The append method essentially operates on an object, so the list has changed after calling the function, but the id has not changed, and it is still the original object. Therefore, if the function receives a reference to a mutable object (such as a dictionary or list), it can modify the original value of the object-equivalent to passing the object by "passing by reference"

Example 2

def test2(p):
p = "i in test2"
print(p,id(p))
str = "hello word"
test2(str)
print(str,id(str))

Output:

i in test2 2885210784112
hello word 2885210784048
id is not the same, so it is not the same object, which means that we are still passing the python basic tutorial reference. Therefore, if the function receives a reference to an immutable object (such as a number, character, or tuple), it cannot directly modify the original object-it is equivalent to passing the object by "passing by value".

to sum up:

Python parameter passing must be the "passing object reference" method. This method is equivalent to a combination of passing by value and passing by reference. If the function receives a reference to a mutable object (such as a dictionary or list), it can modify the original value of the object-equivalent to passing the object by reference. If the function receives a reference to an immutable object (such as a number, character, or tuple), it cannot directly modify the original object-it is equivalent to passing the object by "passing by value".

Guess you like

Origin blog.csdn.net/chinaherolts2008/article/details/112910830