Convert String to Object name

前端 未结 2 1811
失恋的感觉
失恋的感觉 2021-01-05 07:18

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:

<         


        
2条回答
  •  心在旅途
    2021-01-05 07:44

    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).

提交回复
热议问题