This article mainly introduces the python dynamic variable loading example. For more information, see. after a program is started, all program files will be loaded into the memory, in this way, if the program text changes again, it will not affect the running of the current program, which is a protection for the program.
However, for languages like python, we sometimes use the form of "from module import variable name". if this variable is directly defined in the file, these variables are defined and assigned values at the beginning of the program, and the value remains unchanged during running. If you want to rewrite this module during running, the changed variable value cannot be used.
To solve this problem, you can define the variables in this module in the function, and the function is dynamically executed when the program is running, in this way, the latest value of the variable can be obtained. The following is an example:
First, if the function is not used:
The code is 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
In this way, when test1.py is executed, the result is still 'Hello world' instead of 'Hello you', indicating that the variable has been loaded into the memory, this module file has been overwritten on the hard disk.
Next, use the function:
The code is 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
In this way, the print result is hello you, because the function is run first, and then the variable is obtained through the function, so that the new value is obtained.