使用字符串变量作为变量名我有一个变量,给它分配了一个字符串,我想根据这个字符串定义一个新变量。foo = "bar"foo = "something else" # What I actually want is:bar = "something else"
3 回答

米琪卡哇伊
TA贡献1998条经验 获得超6个赞
exec
>>> foo = "bar">>> exec(foo + " = 'something else'")>>> print bar something else>>>

叮当猫咪
TA贡献1776条经验 获得超12个赞
my_data = {}foo = "hello"my_data[foo] = "goodbye"assert my_data["hello"] == "goodbye"

蓝山帝景
TA贡献1843条经验 获得超7个赞
setattr
name = 'varname'value = 'something'setattr(self, name, value) #equivalent to: self.varname= 'something'print (self.varname)#will print 'something'
添加回答
举报
0/150
提交
取消