可能重复:
How do I do variable variables in Python?
我有一个分配了字符串的变量,我想基于该字符串定义一个新变量。
foo = "bar"
foo = "something else"
# What I actually want is:
bar = "something else"
发布于 2012-07-19 12:01:43
您可以使用exec
来实现此目的:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
发布于 2012-07-19 12:05:06
相反,使用字典会让你更快乐:
my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
发布于 2012-07-19 12:10:17
您可以使用setattr
name = 'varname'
value = 'something'
setattr(self, name, value) #equivalent to: self.varname= 'something'
print (self.varname)
#will print 'something'
但是,因为您应该通知对象接收新变量,所以这只在类或模块内部有效。
https://stackoverflow.com/questions/11553721
复制相似问题