Home  >  Article  >  Backend Development  >  python动态加载变量示例分享

python动态加载变量示例分享

WBOY
WBOYOriginal
2016-06-16 08:45:091020browse

众所周知,程序在启动后,各个程序文件都会被加载到内存中,这样如果程序文本再次变化,对当前程序的运行没有影响,这对程序是一种保护。

但是,对于像python这样解释执行的语言,我们有时候会用到“from 模块 import 变量名”这样的形式,如果这个变量直接被定义在文件当中,那么这些变量在程序开始时就会被定义、赋值,运行过程中值不变。如果打算在运行过程中对这个模块进行重写,那么更改后的变量值是无法被使用的。

对于这个问题,可以换一种思路,将这个模块中的变量定义在函数里,而函数是在程序运行的时候动态执行的,这样就能够获取到变量的最新值。下面是例子:

首先,不使用函数的情况: 

复制代码 代码如下:

#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

这样,执行test1.py的时候,出现的结果仍然是'hello world',而非‘hello you',说明变量已经加载到内存中,尽管该模块的文件在硬盘上已经被重写。

接下来,使用函数的情况:

复制代码 代码如下:

#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

这样,print出来的结果就是hello you 了,因为在运行的时候,先执行了一遍这个函数,再通过函数获取了这个变量,这样就会获得新值。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn