例:
exec("""a = 2def foo(): print afoo()""") in {},{}
当你尝试这个:
nameError: global name 'a' is not defined解决方法 乍一看对我来说也很奇怪.但是有了更多输出我找到了原因:
>>> g,l = {},{}>>> print ID(g),ID(l)12311984 12310688>>>>>> exec '''... a = 2... print 'a' in globals(),'a' in locals(),ID(globals()),ID(locals())... def f():... print 'a' in globals(),ID(locals())... f()... ''' in g,lFalse True 12311984 12310688False False 12311984 12311264
如http://effbot.org/pyfaq/what-are-the-rules-for-local-and-global-variables-in-python.htm所述:
In Python,variables that are only referenced insIDe a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body,it’s assumed to be a local. If a variable is ever assigned a new value insIDe the function,the variable is implicitly local,and you need to explicitly declare it as global.
所以一个解决方案是对全局变量和本地变量使用相同的dict:
>>> l = {}>>> exec '''... a = 2... def f():... print a... f()... ''' in l,l2总结
以上是内存溢出为你收集整理的Python exec中的范围全部内容,希望文章能够帮你解决Python exec中的范围所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)