We usually write Python The program is full of functions , Including the system's own functions and user-defined functions , When we call the function, we directly pass in the parameters and wait to receive the return value , It's not easy to use . So do you know how the parameters of a function are passed , Is it value passing or reference passing , What is value passing and reference passing ?

This problem is quite difficult for many beginners , See here you can pause , Think for yourself , See if you really understand . A lot of people just know the concept, but let him say he doesn't know , If you still feel vague after thinking , Look down carefully , Today, I will take you to deeply analyze the parameter passing mechanism of functions .

In order to understand the parameter passing mechanism of function , You have to thoroughly understand formal and actual parameters first . For example, the following sayHello function , In parentheses name Is the parameter , And when you call a function, you pass name Is the argument .

def sayHello(name): # name It's a formal parameter     print("Hello %s" % name)

name = "hanmeimei" # name Is the actual parameter sayHello(name)
# Output results Hello hanmeimei

Value passed OR reference

We said that up there , When we call a function, we pass the actual parameters to the formal parameters . And there are two kinds of transmission , It is the value passing and reference passing that we mentioned above .

seeing the name of a thing one thinks of its function , The so-called value transfer is to copy the value of the actual parameter to the formal parameter in the process of transfer , In this way, even if the formal parameters are modified during the execution of the function , And the formal parameters don't change , Because they don't interfere with each other . The reference passing is the value passing the reference of the actual parameter to the actual parameter , So they both point to the same memory address , The formal parameters are modified during the execution of the function , The formal parameters will also be = Be modified .

For the smooth development of the story , Let's take a look first Python About the assignment of variables in .

>>> a = 10>>> b = a>>> a = a + 10>>> a20>>> b10>>>

In the above example , We declared a variable a, Its value is 10, And then b Point to a, This is the layout in memory, which is like this , Variable a and b Will point to the same object 10, Rather than to b Regenerate a new object .


Thus we can see that , The same object can be referenced by multiple objects .

When performing the a = a + 10 after , Because integers are immutable objects , So it's not going to 10 become 20, It's about creating a new object 20 , then a Will point to this new object .b Or point to old objects 10.


therefore , The last is a by 20, and b by 10.

After understanding the assignment process above , Let's take a look at parameter passing . Old rules , Let's just look at the examples , Code doesn't lie .

def swap(a, b):    a, b = b, a    print("in swap a = %d and b = %d " % (a, b))

a = 100b = 200swap(a, b)print("in main a = %d and b = %d " % (a, b))
## Output results in swap a = 200 and b = 100 in main a = 100 and b = 200

We are in function swap China exchange a and b Value , And then in the main function and swap Function output its result , From the results ,swap Functions don't change the actual parameters a,b Value , So we can come to a conclusion ,Python Function parameters are passed by value .

Don't worry. , Let's look at one more example .

def swap(list):    list.append(4)    print("in swap list is %s " % list)

list_x = [1, 2, 3]swap(list_x)print("in main list is %s " % list_x)
## Output results in swap list is [1, 2, 3, 4] in main list is [1, 2, 3, 4]

Why , The value has been changed , That's just the reference passing . therefore , We came to the conclusion that ,Python Function parameters are passed by reference .

This is a little too lax , In fact, our second example above is a little less rigorous , I changed it a little swap function , We're looking at the test results .

def swap(list):    list = list + [4]    print("in swap list is %s " % list)
## Output results in swap list is [1, 2, 3, 4] in main list is [1, 2, 3]

We just changed swap A line of code inside the function , The result is totally different . In order to better understand its implementation process , I drew a picture .


In the first one about list In the case of , We first declare a list , The element is [1,2,3], At this time, the memory layout is as shown in step 1 in the figure above .list_x The memory address is OX7686934F Region .

When calling swap Function will list_x Pass to formal parameters list when , The address will be delivered directly to ,list It will also point to this address , As shown in step 2 .

Last , Because the list is variable , So when list When adding elements to the list ,list_x Naturally it will be affected , Because they point to the same block of memory .

therefore , Here is also value passing , It's just that the value passed is the memory address of the object .

The second one is about list In the case of , We are right. swap Function has been modified , The execution process is shown in the figure below .


In execution swap Function is the same as the example above . stay swap Internal function list = list + [4] It means to create a new one and add an element at the end 4 New list of , And let list Point to this new memory address  OX7686936A. Because a new object is generated , Nothing to do with the original object , therefore list_x Unaffected .

In short , Just figure out the difference between changing a variable and reassigning it , In the first example, we changed the value of the variable , So when the function is finished, all variables that point to the object will be affected . And reassignment is equivalent to regenerating a new object and doing operations on the new object , So old objects are not affected .

If we want to change objects in functions , First, variable data types can be passed in ( list , Dictionaries , aggregate ), Direct change ; Second, you can create a new object , Modify and return to . The latter is recommended , The expression is clear , It's not easy to make mistakes. .


This paper introduces Python Function parameter passing mechanism . Understand the parameter transfer process and the underlying implementation details , There will be fewer unnecessary low-level errors when writing code .

Last , Whether it's value passing or reference passing , We just need to focus on whether new pairs of objects will be generated inside the function . Functions that operate on the original object , Will affect the actual parameters passed ; All operations that generate new objects , Does not affect the actual parameters passed .

Code address

Sample code :https://github.com/JustDoPython/python-100-day/tree/master/day-115

Series articles

   The first 114 God : Three board model algorithm project actual combat

   The first 113 God :Python XGBoost Algorithm project actual combat

   The first 112 God : Monte Carlo of machine learning algorithm

   The first 111 God :Python Garbage collection mechanism

from 0 Study Python 0 - 110 Summary of the grand collection