Python - 变量名中的变量?

我不确定这是否已经在这里,如果是,我很抱歉。


我试图将一个变量的输出(在这种情况下是一个字符串)放入另一个变量“名称”中(如果它被调用的话),但使用exec并不理想,我不想将它全部放入 exec 函数中。


有什么办法可以做我在这段代码中尝试做的事情吗?


world = world[(x,y)].type 

exec("if blocks." + world + ".hasUp == True:")

    tick(taX,taY)


心有法竹
浏览 238回答 1
1回答

幕布斯6054654

使用__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'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python