在函数中使用exec设置变量

2024-09-26 18:09:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始自学Python,我需要这个脚本的一些帮助:

old_string = "didnt work"   
new_string = "worked"

def function():
    exec("old_string = new_string")     
    print(old_string) 

function()

我想这么做old_string = "worked"


Tags: 脚本newstringdeffunctionoldworkexec
2条回答

另一种让exec从函数内部更新全局变量的方法是将globals()传递到函数中。

>>> def function(command):
...    exec(command, globals())
...
>>> x = 1
>>> function('x += 1')
>>> print(x)
2

locals()不同,更新globals()字典总是需要更新相应的全局变量,反之亦然。

你就快到了。您正试图修改全局变量,因此必须添加global语句:

old_string = "didn't work"
new_string = "worked"

def function():
    exec("global old_string; old_string = new_string")
    print(old_string)

function()

如果运行以下版本,您将看到您的版本中发生了什么:

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中修改函数的局部变量,这基本上是未定义的行为。请参阅^{} docs中的警告:

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.

以及^{}上的相关警告:

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.

相关问题 更多 >

    热门问题