我不确定这是否已经在这里,如果是,我很抱歉。我试图将一个变量的输出(在这种情况下是一个字符串)放入另一个变量“名称”中(如果它被调用的话),但使用exec并不理想,我不想将它全部放入 exec 函数中。有什么办法可以做我在这段代码中尝试做的事情吗?world = world[(x,y)].type exec("if blocks." + world + ".hasUp == True:") tick(taX,taY)
1 回答

幕布斯6054654
TA贡献1876条经验 获得超7个赞
使用__dict__:
>>> def foo():
... pass
...
>>> a = "hello"
>>> foo.__dict__[a] = "world"
>>> foo.hello
'world'
globals() 对于全局变量(返回全局变量字典):
>>> name = "may"
>>> globals()[name] = "the force be with you"
>>> may
'the force be with you'
locals() 对于局部变量:
>>> name = "life"
>>> locals()[name] = "was like a box of chocolates"
>>> life
'was like a box of chocolates'
添加回答
举报
0/150
提交
取消