在函数内使用 exec 设置变量 [英] Setting variables with exec inside a function

查看:34
本文介绍了在函数内使用 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 function exec() returns.

以及关于locals()<的相关警告/a>:

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.

这篇关于在函数内使用 exec 设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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