Search code examples
pythonpython-2.7classvariablesenumeration

How to create variables with a loop?


So, I want to pragmatically create class instances from a list of lists I'm looping over. How to do that?

class foo:
   def __init__(self, first, second):
      self.first = first
      self.second = second

my_list = [[a_0, a_1, a_2], [b_0, b_1, b_2], [c_0, c_1, c_2]]
i = 1
instance_name = instance_
for list in my_list:
   x = instance_name + str(i)
   x = foo(list[0], list[2])
   i += 1

I know that the second x in my loop is totally wrong. But I need to be able to call my instances in the future with the value of x. Any help?


Solution

  • As the comment from @roganjosh says the data of variable x is being over written, so if you want to create variables use locals() but its not a good practice. Its better you go for dictionary to store the instances i.e

    class foo:
        def __init__(self, first, second):
            self.first = first
            self.second = second
    
    a_0,a_1,a_2 = 1,2,3
    b_0,b_1,b_2 = 4,5,6
    c_0,c_1,c_2 = 7,8,9
    
    my_list = [[a_0, a_1, a_2], [b_0, b_1, b_2], [c_0, c_1, c_2]]
    
    for i,li in enumerate(my_list):
        locals()['instance_{}'.format(i+1)] = foo(li[0], li[2])
    # instance_1.first 
    # 1
    # instance_3.first
    # 7
    

    A dictionary approach is that :

    x = {'instance_{}'.format(i+1): foo(li[0], li[2]) for i,li in enumerate(my_list) }
    
    #x['instance_1'].first
    #1