简体   繁体   English

function 中的命令执行,名称错误 - python3

[英]Command exec in a function, name error - python3

I'm begginer in Python and I'm in front of a problem that I can't understand.我是 Python 的初学者,我遇到了一个我无法理解的问题。 I tried to just define a variable with a exec() and then just print it.我试图用 exec() 定义一个变量,然后打印它。 And it's working well.它运作良好。 BUT when I do the same code in a function, it's not working...但是当我在 function 中执行相同的代码时,它不起作用......

Example:例子:

def fonct():
    possibilite = [0,1,2,3]
    testc = 0
    testl = 1
    commande = "proba"+str(testc+1)+str(testl)+" = possibilite"
    exec(commande)
    print(commande)
    print(proba11)

The same thing but not in a function has for result, that the command print(proba11) returns [0,1,2,3] so it works.同样的事情,但不是在 function 有结果,命令 print(proba11) 返回 [0,1,2,3] 所以它工作。 But for the example I got this:但对于这个例子,我得到了这个:

proba11 = possibilite
NameError: name 'proba11' is not defined

There is no stories about globals or locals, everything is local...没有关于全球人或本地人的故事,一切都是本地人......

Updating the local variables with exec() in Python 3 is tricky due to the way local variables are stored.由于局部变量的存储方式,在 Python 3 中使用exec()更新局部变量很棘手。 It used to work in Python 2.7 and earlier.它曾经在 Python 2.7 及更早版本中工作。

To workaround this, you need to要解决此问题,您需要

  • Pass an explicit locals dictionary to exec将显式locals字典传递给exec
  • Grab the newly defined variable from the updated locals dictionary从更新的本地字典中获取新定义的变量

Like so:像这样:

def fonct():
    possibilite = [0, 1, 2, 3]
    testc = 0
    testl = 1
    varname = "proba" + str(testc + 1) + str(testl)
    commande = varname + " = possibilite"
    _locals = locals()
    exec(commande, globals(), _locals)
    proba11 = _locals[varname]
    print(proba11)

Which works as expected.哪个按预期工作。

You can read more about it here:你可以在这里读更多关于它的内容:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM