我认为下面的代码完全描述了这个问题。为什么在Test2函数中x没有被定义?为什么Test3函数不会返回错误?python的exec函数的奇怪行为
>>> def Test1():
exec('x=2')
print(str(x))
>>> Test1()
2
>>> def Test2():
global x
exec('x=2')
print(str(x))
>>> Test2()
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
Test2()
File "<pyshell#38>", line 4, in Test2
print(str(x))
NameError: global name 'x' is not defined
>>> def Test3():
global x
x=2
print(str(x))
>>> Test3()
2
你想做什么?不要使用'global',也不要使用'exec';他们导致设计糟糕的代码,而在'exec'中,代码不安全。 – 2012-07-25 21:37:32
我试图从txt文件加载我的基于字典的databese :) – 2012-07-25 21:51:18
是的,不要这样做。相反,将数据库存储为JSON,并使用'mydata = json.load(open('mydb.txt'))'加载它'' – 2012-07-25 21:53:08