【发布时间】:2013-08-13 18:46:19
【问题描述】:
假设我有两个脚本:
test_fun1.py
a = 1
def test1():
print a
execfile('test_fun2.py')
test1()
test_fun2.py
b = 2
def print_a():
print 'a'
def test2():
print_a()
print b
test2()
当我运行 test_fun1.py 时,我收到此错误:
NameError: global name 'print_a' is not defined
如果我在test2() 中排除print_a(),a 和b 都会被打印出来。为什么变量会设置为全局而函数不会?
【问题讨论】:
-
你的意思是 a 和 b 都是从 test_fun2.py 打印的? (或者它可能来自test1())?另外,您是否考虑过只导入外部脚本?
-
也许这对你有帮助? stackoverflow.com/questions/2904274/…
-
@sihrc:当 print_a() 从代码中排除时,a 从 test1() 打印,b 从 test2() 打印。
-
那么,变量就不是“全局的”了。
-
@sihrc:我的意思是我可以在函数内部使用 a 和 b,尽管它们是在函数外部定义的。不过,我还没有使用“global”命令将它们声明为全局。