exec() 和变量范围

exec() and variable scope(exec() 和变量范围)

本文介绍了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 1Case 2 在 print 语句中未定义 aaa.
  • 案例 3 有效.aaaCase 1Case 2 中究竟存在哪里?
  • 有没有办法在没有 global 声明的情况下访问案例 1 中的 aaa?
    • Case 1 and Case 2 have aaa undefined in the print statement.
    • Case 3 works. Where does aaa actually exist in Case 1 and Case 2?
    • Is there a way to access aaa in Case 1 without a global declaration?
    • 推荐答案

      来自 文档:

      注意:默认的 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 function exec() 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() 和变量范围

基础教程推荐