使用字符串变量作为变量名[重复]
- 2024-12-16 08:35:00
- admin 原创
- 132
问题描述:
我有一个分配了字符串的变量,并且我想基于该字符串定义一个新变量。
foo = "bar"
foo = "something else"
# What I actually want is:
bar = "something else"
解决方案 1:
您可以使用exec
:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
解决方案 2:
你会更乐意使用字典:
my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"
解决方案 3:
您可以使用setattr
name = 'varname'
value = 'something'
setattr(self, name, value) #equivalent to: self.varname= 'something'
print (self.varname)
#will print 'something'
但是,由于您应该通知对象接收新变量,因此这仅在类或模块内部有效。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD