Thursday, September 26, 2013
Python开发中全局变量问题备忘
在项目中遇到的一个全局变量问题,简单记录下做个备忘。
场景:
根目录下有一个文件a.py,目录test;目录test中有__init__.py,b.py,c.py两个环境。其中a.py是主程序。
环境:
Python 2.7.1
程序:
b.py
----------------------------------------------------------------
num = 1
c.py
----------------------------------------------------------------
from b import num
def printnum1():
print 'printnum1: num = ', num
def printnum2():
from b import num
print 'printnum2: num(re-import) = ', num
a.py
----------------------------------------------------------------
import test
from test.b import num
from test.c import printnum1, printnum2
print 'num = ', num
num = 3
print 'num = ', num
print 'test.b.num = ', test.b.num
printnum1()
printnum2()
test.b.num = 4
print 'num = ', num
print 'test.b.num = ', test.b.num
printnum1()
printnum2()
输出结果:
----------------------------------------------------------------
num = 1
num = 3
test.b.num = 1
printnum1: num = 1
printnum2: num(re-import) = 1
num = 3
test.b.num = 4
printnum1: num = 1
printnum2: num(re-import) = 4
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment