Thirteen, python basis: Scope 1 (memory reference and release) variables

Thirteen, python basis: Scope 1 (memory reference and release) variables

Before addressing the scope of the variable, we first execution order python interpreter runtime code, memory allocation, memory references, memory release mechanism to find out.

1, when you run a py file, python interpreter how this works?

When pycharm run a py file, right-click on our run, it will be executed. This time, python interpreter to explain line by line from top to bottom translated into machine code.
Take the following example to illustrate:

i = 0
def add(a, b=1):
    i += a
    
add(1)
print(i)

This example is no concrete meaning, but can analyze the interpreter how to run.
When you run right, from top to bottom interpreter scan code, you encounter i = 0, to open up a place in the memory space, storage i corresponding value. Continue to see down the definition of the function add, at this time it does not call the function, it will first look inside the function there is a default parameter b = 1, it has opened up a block of memory to store the value of b. Continue down to see the add function calls, so it returns to this function is called again, and finally saw print function call, it is output in the console. At the end of the output, the implementation of the entire file over, previously stored in the memory of each variable on the release out.

This whole process we are generally clear.

But note that: memory problems cited several related mechanisms

1, how to know where the presence of variables in memory?

We can use the id (a), to get the memory address stored in a variable.

2, the process for re-assignment to a variable, the interpreter whether to re-open the memory space for it;

Will do.
Here Insert Picture Description
Here you can see twice re-assignment to the same variable a, its memory address has changed. Description interpreter again opened up memory space for the variables.

3, when a variable to be modified, is interpreted to modify the original address, or to change it after stored in a new memory space;

This depends on what type of variable, what changes the operation performed yes.
This problem is rather complicated. I was doing the course of the project have encountered this problem, if you are interested, I can see another article:
Python pit: Use the empty list as the default parameter, so I doubt encountered a supernatural codes

There is also talked about problems in the framework django memory release, you perform with a py file alone is not the same.

Finally, the issue involves memory aspects, I speak here not many, but the novice to know almost all the same, want to know more, you can search other people's articles.

Published 55 original articles · won praise 77 · views 9494

Guess you like

Origin blog.csdn.net/Jacky_kplin/article/details/104817264