[英]Setting variables with exec inside a function
I just started self teaching Python, and I need a little help with this script:我刚开始自学 Python,我需要一些关于这个脚本的帮助:
old_string = "didnt work"
new_string = "worked"
def function():
exec("old_string = new_string")
print(old_string)
function()
I want to get it so old_string = "worked"
.我想得到它
old_string = "worked"
。
You're almost there.您快到了。 You're trying to modify a global variable so you have to add the
global
statement:您正在尝试修改全局变量,因此您必须添加
global
语句:
old_string = "didn't work"
new_string = "worked"
def function():
exec("global old_string; old_string = new_string")
print(old_string)
function()
If you run the following version, you'll see what happened in your version:如果您运行以下版本,您将看到您的版本中发生了什么:
old_string = "didn't work"
new_string = "worked"
def function():
_locals = locals()
exec("old_string = new_string", globals(), _locals)
print(old_string)
print(_locals)
function()
output:输出:
didn't work
{'old_string': 'worked'}
The way you ran it, you ended up trying to modify the function's local variables in exec
, which is basically undefined behavior.你运行它的方式,你最终试图在
exec
中修改函数的局部变量,这基本上是未定义的行为。 See the warning in the exec
docs :请参阅
exec
文档中的警告:
Note: The default locals act as described for function
locals()
below: modifications to the default locals dictionary should not be attempted.注意:默认locals的行为如下面函数
locals()
所述:不应尝试修改默认locals字典。 Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()
returns.如果您需要在函数
exec()
返回后查看代码对局部变量的影响,请传递显式局部变量字典。
and the related warning on locals()
:以及有关
locals()
的相关警告:
Note: The contents of this dictionary should not be modified;
注意:不得修改本词典的内容; changes may not affect the values of local and free variables used by the interpreter.
更改可能不会影响解释器使用的局部变量和自由变量的值。
As an alternative way of having exec
update your global variables from inside a function is to pass globals()
into it.作为让
exec
从函数内部更新全局变量的另一种方法是将globals()
传递给它。
>>> def function(command):
... exec(command, globals())
...
>>> x = 1
>>> function('x += 1')
>>> print(x)
2
Unlike locals()
, updating the globals()
dictionary is expected always to update the corresponding global variable, and vice versa.与
locals()
不同,更新globals()
字典应该总是更新相应的全局变量,反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.