Python函数中使用exec要注意局部变量问题
(2013-06-23 01:51:40)
写程序时需要动态赋值,于是乎应用exec函数,发现以下代码可以正常运行
exec('a'+str(i)+'=i')
而用如下代码段封装到函数内后无法运行
def attempt(i):
exec('a=I')
return a
a = attempt(i)
显示 Variable a is not defined
查找资料得到解决方法,通过如下代码可正常运行
def attempt(i):
exec('a=i')
return locals()['a']
a = attempt(i)
完美解决。
原文见:
http://blog.sina.com.cn/s/blog_62d4d5900101a0bp.html