Convert String to Object name

蓝咒 提交于 2019-11-30 05:15:11

问题


I needed help on this one. How do I convert a string into a variable/object/instance name, since I don't know how to categorize this.
Assuming my code is:

a = {}
b = {}

class Test:
    def getKeys(self, var):
        return var.keys() #where var refers to the dictionary and its a string initially

回答1:


It's been forever since I've done anything with Python but I do remember having this problem once. I suggest you look into the eval() function.




回答2:


If I understand correctly, your variable var is a string that might be "a" or "b". You want to use that letter to pick the correct dictionary global variable to look in.

I suggest putting your dictionaries into another dictionary, with keys you can use to look it up by name:

my_dicts = {"a":a, "b":b}

class Test:
    def getkeys(self, dict_name):
        return my_dicts[dict_name].keys()

However, this may be simply an issue of design. Instead of sending a variable name to the getkeys method, why not simply send the dictionary itself and use your current code?

Instead of Test().getkeys("a"), call Test().getkeys(a) (no quotation marks).



来源:https://stackoverflow.com/questions/15193032/convert-string-to-object-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!