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

sar*_*jit 0 python

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

class test1:
    pass

class test2:
   pass

test1_dict = {}
test2_dict = {}

testvariable = "test1"
Run Code Online (Sandbox Code Playgroud)

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

例如

if testvariable == "test1":
    test1inst = test1()
    test1_dict["test1"] = test1inst
elif testvariable == "test2":
    test2inst = test2()
    test2_dict["test2"] = test2inst
Run Code Online (Sandbox Code Playgroud)

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

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

Dan*_*man 10

有几乎从来没有一个很好的理由来查找这样的名字.Python有一个非常好的数据结构,用于将名称映射到对象,这是一个字典.如果你发现自己说"我需要动态查找某些东西",那么dict就是答案.在你的情况下:

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