使用字符串变量作为变量名[复制]

时间:2022-12-22 23:49:26

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

可能重复:我如何在Python中执行变量变量?

I have a variable with a string assigned to it and I want to define a new variable based on that string.

我有一个变量,并为其分配了一个字符串,我想根据该字符串定义一个新变量。

foo = "bar"
foo = "something else"   

# What I actually want is:

bar = "something else"

3 个解决方案

#1


117  

You can use exec for that:

您可以使用exec:

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

#2


97  

You will be much happier using a dictionary instead:

你会更乐意使用字典:

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

#3


63  

You can use setattr

你可以使用setattr

name= 'varname'
value= 'something'

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

print self.varname
#will print 'something'

But, since you should inform an object to receive the new variable, I think this only works inside classes.

但是,既然你应该通知一个对象接收新变量,我认为这只适用于类内部。

#1


117  

You can use exec for that:

您可以使用exec:

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

#2


97  

You will be much happier using a dictionary instead:

你会更乐意使用字典:

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

#3


63  

You can use setattr

你可以使用setattr

name= 'varname'
value= 'something'

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

print self.varname
#will print 'something'

But, since you should inform an object to receive the new variable, I think this only works inside classes.

但是,既然你应该通知一个对象接收新变量,我认为这只适用于类内部。