exec() and variable scope(exec() 和变量范围)
问题描述
我确定有人问过并回答过,但我找不到具体的:
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() 和变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:exec() 和变量范围
基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
