问题描述
我确定有人问过并回答过,但我找不到具体的:
I'm sure this has been asked and answered, but I couldn't find it specifically:
我刚刚开始学习 Python,但我不了解变量范围问题.
I'm just picking up Python and I'm not understanding a variable scope issue.
我已将问题简化为:
案例一:
def lev1():
exec("aaa=123")
print("lev1:",aaa)
lev1()
案例 2:
def lev1():
global aaa
exec("aaa=123")
print("lev1:",aaa)
lev1()
案例 3:
def lev1():
exec("global aaa ; aaa=123")
print("lev1:",aaa)
lev1()
Case 1和Case 2在 print 语句中未定义aaa.案例 3有效.aaa在Case 1和Case 2中究竟存在哪里?- 有没有办法在没有
global声明的情况下访问案例 1 中的aaa? Case 1andCase 2haveaaaundefined in the print statement.Case 3works. Where doesaaaactually exist inCase 1andCase 2?- Is there a way to access
aaain Case 1 without aglobaldeclaration?
推荐答案
来自 文档:
注意:默认的 locals 行为与函数 locals() 下面:不应尝试修改默认的 locals 字典.如果您需要在函数 exec() 返回.
Note: The default locals act as described for function
locals()below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()returns.
换句话说,如果你用一个参数调用 exec,你不应该尝试分配任何变量,Python 也不承诺如果你尝试会发生什么.
In other words, if you call exec with one argument, you're not supposed to try to assign any variables, and Python doesn't promise what will happen if you try.
您可以通过显式传递 globals() 将 executed 代码分配给全局变量.(如果有明确的 globals dict 而没有明确的 locals dict,exec 将对全局和本地使用相同的 dict.)
You can have the executed code assign to globals by passing globals() explicitly. (With an explicit globals dict and no explicit locals dict, exec will use the same dict for both globals and locals.)
def lev1():
exec("aaa=123", globals())
print("lev1:", aaa)
lev1()
这篇关于exec() 和变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)