As we all know, after the program starts, each program file will be loaded into memory, so if the program text changes again, to the current program operation has no effect, this is a program is a protection.
However, for languages like python that interpret execution, we sometimes use the "from module import variable name" form, if the variable is directly defined in the file, then these variables will be defined at the beginning of the program, assigned value, the value of the operation process is unchanged. If the module is intended to be rewritten during the run, the changed value of the variable cannot be used.
For this problem, you can change the way the variables in this module are defined in the function, and the function is executed dynamically when the program is running, so that you can get the latest value of the variable. Here is an example:
First, no function is used:
Copy the Code code as follows:
#model1. py
P_hello = ' Hello world! '
#test1. py
From Model1 import P_hello
File = open (' model1.py ', ' W ')
File.write ("P_hello = '%s! '"% (' Hello you '))
File.close ()
Print P_hello
Thus, when executing the test1.py, the result is still ' Hello World ', not ' hello you ', stating that the variable has been loaded into memory, although the module's file has been rewritten on the hard disk.
Next, use the function's case:
Copy the Code code as follows:
#model1. py
def rule ():
P_hello = ' Hello world! '
Return locals ()
#test1. py
From model1 Import rule
File = open (' model1.py ', ' W ')
File.write (' Def rule (): \ n ')
File.write ("P_hello = '%s! ') \ n "% (' Hello you '))
File.write ("return locals () \ n")
File.close ()
P_hello = Rule () [' P_hello ']
Print P_hello
So, the result of print is Hello you, because at run time, the function is executed first, and then through the function to obtain the variable, so that the new value will be obtained.