我知道其他一些语言,如PHP,支持“变量变量名”的概念——也就是说,字符串的内容可以用作变量名的一部分。

我听说这通常是一个坏主意,但我认为它可以解决我的Python代码中的一些问题。

在Python中可以做这样的事情吗?会出什么问题?


如果您只是试图通过名称查找现有变量,请参见如何通过(字符串)名称选择变量。但是,首先考虑是否可以按照这个问题中的建议重新组织代码以避免这种需要。


当前回答

如果你不想使用任何对象,你仍然可以在当前模块中使用setattr():

import sys
current_module = module = sys.modules[__name__]  # i.e the "file" where your code is written
setattr(current_module, 'variable_name', 15)  # 15 is the value you assign to the var
print(variable_name)  # >>> 15, created from a string

其他回答

您可以使用字典来实现这一点。字典是键和值的存储。

>>> dct = {'x': 1, 'y': 2, 'z': 3}
>>> dct
{'y': 2, 'x': 1, 'z': 3}
>>> dct["y"]
2

可以使用可变键名实现可变变量的效果,而不存在安全风险。

>>> x = "spam"
>>> z = {x: "eggs"}
>>> z["spam"]
'eggs'

如果你想做些什么

var1 = 'foo'
var2 = 'bar'
var3 = 'baz'
...

清单可能比字典更合适。list表示对象的有序序列,索引为整数:

lst = ['foo', 'bar', 'baz']
print(lst[1])           # prints bar, because indices start at 0
lst.append('potatoes')  # lst is now ['foo', 'bar', 'baz', 'potatoes']

对于有序序列,列表比使用整数键的字典更方便,因为列表支持索引顺序迭代、切片、追加和其他需要使用字典进行笨拙的键管理的操作。

如果你不想使用任何对象,你仍然可以在当前模块中使用setattr():

import sys
current_module = module = sys.modules[__name__]  # i.e the "file" where your code is written
setattr(current_module, 'variable_name', 15)  # 15 is the value you assign to the var
print(variable_name)  # >>> 15, created from a string

SimpleNamespace类可以使用setattr或SimpleNamespace的子类来创建新属性,并创建自己的函数来添加新的属性名(变量)。

from types import SimpleNamespace

variables = {"b":"B","c":"C"}
a = SimpleNamespace(**variables)
setattr(a,"g","G")
a.g = "G+"
something = a.a

当你想使用变量变量时,最好使用字典。所以与其写

$foo = "bar"
$$foo = "baz"

你写

mydict = {}
foo = "bar"
mydict[foo] = "baz"

这样就不会意外地覆盖先前存在的变量(这是安全方面的问题),并且可以使用不同的“名称空间”。

这应该是非常危险的…… 但是你可以使用exec():

a = 'b=5'
exec(a)
c = b*2
print (c)

结果: 10