1

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?

4
  • 1
    Append your instances to another list. Currently they're thrown away and overwritten. Commented Nov 12, 2017 at 9:52
  • I tried, but it just won't work. Can you show me an example? Commented Nov 12, 2017 at 10:10
  • @user627154 check out my answer. Commented Nov 12, 2017 at 10:13
  • @user627154 I posted an answer with an example of what roganjosh is telling you to do. Commented Nov 12, 2017 at 10:21

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

Just use list comprehension and construct the instances in that list:

class Foo:

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


# List of parameters to pass to Foo
args_list = [(1, 2), (3, 4), (5, 6)]

# Add an instance of Foo(first num, second num) to the instances list
# for every set of arguments above
instances = [Foo(value[0], value[1]) for value in args_list]


# Print out each of the instances values
for instance in instances:
    print(instance.first, instance.second)
# prints:
# 1 2
# 3 4
# 5 6

# OR you can call an individual instance like so

print(instances[0].first, instances[0].second)
# prints:
# 1 2

4 Comments

Not a bad idea but you've adapted the input to suit your answer. Use list indices to process the OP's actual data
@roganjosh You mean just change the tuples to lists?
No, because OP has 3 items in each sublist so this can't work.
@roganjosh Ah, I understand now. Didn't catch that at first since he was only using the first 2 at the bottom. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.