在函数内部使用exec设置变量
我刚刚开始自学Python,我需要一些有关此脚本的帮助:
I just started self teaching Python, and I need a little help with this script:
old_string = "didnt work"
new_string = "worked"
def function():
exec("old_string = new_string")
print(old_string)
function()
我想得到它,old_string = "worked"
.
您快到了.您正在尝试修改全局变量,因此必须添加global
语句:
You're almost there. You're trying to modify a global variable so you have to add the global
statement:
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()
输出:
didn't work
{'old_string': 'worked'}
运行方式,最终尝试在exec
中修改函数的局部变量,这基本上是未定义的行为.请参见 exec
文档:
The way you ran it, you ended up trying to modify the function's local variables in exec
, which is basically undefined behavior. See the warning in the exec
docs:
注意:默认的 locals 的行为与下面的功能
locals()
所述相同:不应尝试对默认的 locals 字典进行修改.如果需要在函数exec()
返回后查看代码对 locals 的影响,请传递一个明确的 locals 字典.
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 functionexec()
returns.
以及 locals()
上的相关警告:
and the related warning on 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.