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

查看:126
本文介绍了在函数内部使用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() 上的相关警告:

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天全站免登陆