在Python中使用变量值作为字典/类名

在Python中使用变量值作为字典/类名,python,Python,我的要求是使用变量值来引用Python中的类/字典。作为示例,我有以下数据:- class test1: pass class test2: pass test1_dict = {} test2_dict = {} testvariable = "test1" 现在我想检查testvariable的值,创建一个类的实例,并将其附加到字典中 e、 g 在上面的代码中,我必须显式地使用if/else来检查testvariable的值,并相应地执行操作 在我的真实场景中,我可能有

我的要求是使用变量值来引用Python中的类/字典。作为示例,我有以下数据:-

class test1:
    pass

class test2:
   pass

test1_dict = {}
test2_dict = {}

testvariable = "test1"
现在我想检查testvariable的值,创建一个类的实例,并将其附加到字典中

e、 g

在上面的代码中,我必须显式地使用if/else来检查testvariable的值,并相应地执行操作

在我的真实场景中,我可能有多个testvariable值,并且可能有多个地方需要进行if/else检查。那么,我是否有可能直接使用testvariable的值来引用字典/类实例,而不使用if/else。

几乎没有什么好的理由来查找这样的名称。Python有一个非常好的数据结构,用于将名称映射到对象,这就是dict。如果您发现自己说我需要动态查找某些内容,那么dict就是答案。就你而言:

from collections import defaultdict
test_classes = {
    'test1': test1,
    'test2': test2
}
test_instances = defaultdict(list)
test_instances[testvariable].append(test_classes[testvariable])

我同意丹尼尔·罗斯曼的观点,几乎没有一个好的理由这样做。然而,我准备迎接挑战!OP跟着我走,他或她自己承担风险

秘密在于使用Python的exec函数,该函数允许以Python代码的形式执行字符串的内容:

所以

变成

exec("%sinst = %s()" % (testvariable, testvariable))
exec("%s_dict[testvariable] = %sinst" % (testvariable, testvariable))

尽管需要注意的是,testvariable的其他值在OP的情况下不起任何作用,并且在使用exec的情况下会导致NameError异常。

我将结合一些其他帖子,说Python已经有一个字典可以将对象的名称映射到对象。您可以访问本地和全局变量,只要在模块中定义了类,您就可以执行以下操作:

my_inst[testvariable] = locals()[testvariable]()

请看这里:您得到的错误是什么?明白了,我需要使用dict及其方法来管理数据。修正了,谢谢。我同意你的看法,但我在实际代码中实现同样的功能时遇到了问题。请看我的编辑,它更接近我的实际问题。不,坏主意。您可以通过在局部变量或全局变量中查找该类来执行相同的操作:inst=locals[testvariable]非常正确,尽管此方法不需要测试它来自范围中的何处。此外,我认为我的回答清楚地表明,这样做是个坏主意是的,我刚刚见到了exec,然后去了一个非常黑暗的地方
exec("%sinst = %s()" % (testvariable, testvariable))
exec("%s_dict[testvariable] = %sinst" % (testvariable, testvariable))
my_inst[testvariable] = locals()[testvariable]()