2024-05-08 15:23:19 发布
网友
Possible Duplicate:How do I do variable variables in Python?
我有一个分配了字符串的变量,我想基于该字符串定义一个新变量。
foo = "bar" foo = "something else" # What I actually want is: bar = "something else"
你会更乐意用字典来代替:
my_data = {} foo = "hello" my_data[foo] = "goodbye" assert my_data["hello"] == "goodbye"
您可以使用setattr
setattr
name = 'varname' value = 'something' setattr(self, name, value) #equivalent to: self.varname= 'something' print (self.varname) #will print 'something'
但是,由于您应该通知对象接收新变量,我认为这只在类中有效。
您可以使用exec来实现:
exec
>>> foo = "bar" >>> exec(foo + " = 'something else'") >>> print bar something else >>>
你会更乐意用字典来代替:
您可以使用
setattr
但是,由于您应该通知对象接收新变量,我认为这只在类中有效。
您可以使用
exec
来实现:相关问题 更多 >
编程相关推荐