在Python中使用eval或exec设置全局变量

2024-10-05 14:27:35 发布

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

让我先说我完全同意你应该 keep data out of your variable names 但是假设你想要这样的函数:

def setglobal(s, x):
  # Some kind of eval or exec trick like eval(s+' = '+x) so we end up
  # with a global variable whose name is the string s and that has a value of x.

Tags: orof函数yourdatanamesdefeval
2条回答

这似乎有效:

# Take a symbol name s as a string and a value x and eval(s+' = '+x) to set a 
# global variable with name s to value x. For getglobal(s) use eval(s).
def setglobal(s, x):
  exec "global "+s+"; "+s+" = "+repr(x) in globals()

这一定是执行官/考核人的把戏吗?在

def setglobal(s, x):
    globals()[s] = x

相关问题 更多 >