使用字符串变量作为变量nam

2024-05-08 15:23:19 发布

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

Possible Duplicate:
How do I do variable variables in Python?

我有一个分配了字符串的变量,我想基于该字符串定义一个新变量。

foo = "bar"
foo = "something else"   

# What I actually want is:

bar = "something else"

Tags: 字符串in定义foobarvariablesvariabledo
3条回答

你会更乐意用字典来代替:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

您可以使用setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

但是,由于您应该通知对象接收新变量,我认为这只在类中有效。

您可以使用exec来实现:

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 

相关问题 更多 >

    热门问题