无法通过exec()语句更改函数中的全局变量? [英] Cannot change global variables in a function through an exec() statement?

查看:191
本文介绍了无法通过exec()语句更改函数中的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使用exec()从函数内部更改全局变量?当赋值语句在exec()之外时,它可以正常工作.这是我的问题的一个示例:

Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem:


>>> myvar = 'test'
>>> def myfunc():
...     global myvar
...     exec('myvar = "changed!"')
...     print(myvar)
... 
>>> myfunc()
test
>>> print(myvar)
test

推荐答案

docs exec语句采用两个可选表达式,默认为globals()locals(),并且始终在locals()中执行更改(如果有).

Per the docs, the exec statement takes two optional expressions, defaulting to globals() and locals(), and always performs changes (if any) in the locals() one.

因此,请更加明确/具体/精确...:

So, just be more explicit/specific/precise...:

>>> def myfunc():
...   exec('myvar="boooh!"', globals())
... 
>>> myfunc()
>>> myvar
'boooh!'

...,您将可以将全局变量破坏到您的内心.

...and you'll be able to clobber global variables to your heart's contents.

这篇关于无法通过exec()语句更改函数中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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