Search code examples
pythonintrospection

How to obtain a reference to a list from the string name of the list in python


Assume I have a class with three lists as follows:

class Test_Class (): 
     a = [1,2,3]
     b = [4,5,6]
     c = [7,8,9]

I want to define a method in this class, lets call it get_list, such that if I pass the string name of the list, the method returns a reference to the list. For example if I made a call like this: a_list = get_list('b'). Then type >> a_list, at a Python prompt, what would be returned would be [4,5,6]. How can I do this?


Solution

  • If you'd like to create a method in your class I suggest you can use the following.

    class Test_Class (): 
        a = [1,2,3]
        b = [4,5,6]
        c = [7,8,9]
        def get_list(self,lstString):
            return getattr(obj, lstString)
    obj = Test_Class()
    print(obj.get_list('a'))
    print(obj.get_list('b'))
    print(obj.get_list('c'))
    

    We have a function called get_list() which takes an argument lstString - the list you want to receive. Then we make use of getattr(ourObject,variableName).

    output

    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]