0

My requirement is to use variable value for referncing class/dictionaries in Python. As a sample example, I have following data :-

class test1:
    pass

class test2:
   pass

test1_dict = {}
test2_dict = {}

testvariable = "test1"

Now I want to check value of testvariable and create an instance of class and append it in dictionary.

e.g.

if testvariable == "test1":
    test1inst = test1()
    test1_dict["test1"] = test1inst
elif testvariable == "test2":
    test2inst = test2()
    test2_dict["test2"] = test2inst

In the above code, I have to explicitly use if/else to check the value of testvariable and do the operations accordingly.

In my real scenario, I could have multiple values of testvariable and there could be multiple places where if/else check would be required. So, is it possible that somehow, I could be able to use the value of testvariable directly to refer dictionary/class instances without using if/else.

4

3 回答 3

10

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

from collections import defaultdict
test_classes = {
    'test1': test1,
    'test2': test2
}
test_instances = defaultdict(list)
test_instances[testvariable].append(test_classes[testvariable])
于 2013-08-23T08:32:19.147 回答
0

I'm going to combine some other posts and say that Python already has a dictionary that maps names of objects to the object. You can access local and global variables so as long as your class is defined in the module you can do:

my_inst[testvariable] = locals()[testvariable]()
于 2013-08-23T13:36:32.427 回答
0

我同意 Daniel Roseman 的观点,几乎没有充分的理由这样做。不过,我准备好迎接挑战了!OP 跟随我的领导,后果自负。

秘诀是使用 Python 的 exec 函数,它允许将字符串的内容作为 Python 代码执行:

所以,

if testvariable == "test1":
    test1inst = test1()
    test1_dict["test1"] = test1inst
elif testvariable == "test2":
    test2inst = test2()
    test2_dict["test2"] = test2inst

变成

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

尽管需要注意的是 testvariable 的其他值在 OP 的情况下什么都不做,并且在使用 exec() 的情况下会导致 NameError 异常。

于 2013-08-23T10:11:59.350 回答