exec() 和变量作用域 [英] exec() and variable scope

查看:55
本文介绍了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.

我已将问题简化为以下内容:

案例 1:

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 在打印语句中未定义 aaa .
  • Case 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()exec ted 代码分配给全局变量.(使用显式 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() 和变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆