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.
另一种让
exec
从函数内部更新全局变量的方法是将globals()
传递到函数中。与
locals()
不同,更新globals()
字典总是需要更新相应的全局变量,反之亦然。你就快到了。您正试图修改全局变量,因此必须添加
global
语句:如果运行以下版本,您将看到您的版本中发生了什么:
输出:
运行它的方式是,尝试在} docs 中的警告:
exec
中修改函数的局部变量,这基本上是未定义的行为。请参阅^{以及^{} 上的相关警告:
相关问题 更多 >
编程相关推荐