SoFunction
Updated on 2024-10-29

Python Fundamentals of Value Passing and Reference Passing Explained

existpythonIn it, there are two types of arguments passed to a function, one by value and one by reference, and if you happen to know a bit ofcBasically, you can understand the former as passing a formal parameter and the latter as passing a pointer. This post will explore thepythonof value passing and reference passing.

The text depends on thepythonThe environment is.

What is value passing and reference passing

Passing a value can be interpreted as passing a copy, i.e., a copy of the variable, so that modifying the value of the copy will not affect the original value, e.g..

def modify_x(x):
    x = 99
    print("Modified value in function: " , x)
    
x=66
modify_x(x)
print("Value after execution of the modify_x function:" , x)

In the above code, we define a variablexand assigned the value of66after thatxtransmitted to itsmodify_xfunction, in which we set thexassign99, print out the function'sxvalue, the result of the function. Print it again in the main functionxThe value of the

This result is executed as follows.

As in the above code, we are passing in a formal parameter, modifying the formal parameter in the function will not change the original value, this is because the function will run on the stack first, and during the process of running, it will produce a line of localized information, etc. As it happens, the formal parameter we are passing in is the value of that type, so it will be out of the stack after running, and after the stack is out of the memory where the function is located, it will be destroyed, so the local variables in the function will be destroyed along with the stack. So directly modifying the formal parameter is invalid.

This above is value passing.

What is reference passing? Let's take the above example as an analogy, except that the type of the pass is changed, from a numeric type to a dictionary type, such as.

def modify_x(dict):
    dict["x"] = 99
    print("Modified value in number:" , dict)

a={
    "x":66
}
modify_x(a)
print("Value after execution of the modify_x function:", a)

As in the above code, we define a dictionaryaThe dictionary has akeybecause ofxThe value is66The In the case of a call tomodify_xfunction, we willais passed to the function, in which we pass that dictionarykeybecause ofxThe assignment of the99The function ends and prints in the main functionaThe value of the

The result after execution is as follows.

Isn't it surprising that the same code is executed differently when passing a plastic and passing a dictionary? This is becausepythonThe mechanism is such that when it passes that value, it uses a pointer pass, so the value doesn't change, and we call it a reference pass.

Is it possible to intervene whether a parameter is passed by value or by reference?

pythonIt is not possible to intervene in the type of parameter passing, because thepythonunlikecc++As always, you can pass either a formal parameter or a pointer type.

existpythonIn this case, parameter passing is realized by the interpreter, so that ordinary developers, there is no way to directly intervene in the parameter passing method, but you can save the country by making good use of thereturnis one of them. For example, let's modify the code at the beginning so that instead of modifying the value directly, we return a new value, e.g..

def modify_x(x):
    x = 99
    return x

x = 66
x = modify_x(x)
print("Value after execution of the modify_x function:" , x)

When we execute it, the result is.

This is not a modification ofxInstead of receiving the value ofmodify_xThe new value passed back.

Explore how value passing is implemented at the bottom of the hierarchy

The passing of values, as we have described before, is a copy of the data, but is this really the case? Let's write a case study.

def modify_x(x):
    print("In the function:",id(x))

x = 123
print("Outside the function:",id(x))
modify_x(x)

One new piece of knowledge in the above code is the methodid, which allows you to view the memory address of a variable. In the above example, define a shaping in the main functionxThe value is123, before passing it to the function, use theidmethod to look at the memory address of the variable. And then pass it to the functionmodify_xIn this function, it also uses theidmethod to look at the formal parameterxThe address of the

If this is what we think it is, then the two memory addresses should not be the same, so let's run the program.

Noticed that the address inside the function, and outside the function are the same? Hey, what's going on here?

This is because inpythonIn this case, the interpreter is trying to optimize performance and avoid a lot of useless data copying, so when passing, it starts with all the real parameters passed, and only when the value has been modified within the function, a new memory request is made to hold the value. For details, check out this example.

def modify_x(x) :
    print("1 in function:",id(x))
    x = 456
    print("2 in function:",id(x))

x=123
print("Outside function 0:",id(x))
modify_x(x)

With the above code, we have themodify_xfunction, modify the variablexPrinting its memory address both before and after results in the following.

We found that the address memory was pointing to the same address before the modification, and after the modification, the memory address changed.

If we willxIf you replace the data passed by reference, this will not happen, as you can see in the following example.

def modify x(x) :
    print("1 in function:",id(x))
    x[0] = 456
    print("2 in function:",id(x))

x = [123]
print("Outside function 0:",id(x))
modify_x(x)
print("Last value:" , x)

With the above code, we have made a small change where we have shaped the dataxThe list is changed to the list type and finally printed.xto see if it has changed, the code runs as follows.

It was found that the value of the memory address did not change and that thexvalue is really modified in the function.

So by the above example, it can be shown that when the value is passed, the variable address still points to the original address when there is no further modification, and when the value is modified, a new memory address is opened for storing the value. In this way you can avoid copying a lot of data.

And finally, to summarize which types are passed by reference and which are passed by value: the

Passing by reference are lists, dictionaries, collections, custom class instances, and so on.

The value passes are string types, tuples, boolean types, numeric types, and so on.

summarize

This article briefly introduces value passing and reference passing. Value passing, after modifying the value within a function, will not affect the original value, while reference passing, after modifying the value within a function, will impression to the original data. However, there is a small detail, that is, the value of the pass, if you do not modify the value of the time, in fact, the memory address is pointing to the original value of the address, when modifying the value of the time, will really apply for memory to store the modified value, but with the function out of the stack, the function of the data within the local variables, will also be destroyed.

to this article on the basis of Python value transfer and reference transfer detailed article is introduced to this, more related Python value transfer reference transfer content, please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!