Creating instances in a loop with different variables

I am trying to instantiate classes in a loop. All instances must be perceived by another variable. These variables can be a sequence of letters like [a, b, c].

class MyClass(object):
    pass

for i in something:
    #create an instance

If the loop rotates 3 times, I want the loop to do something like this:

a = MyClass()
b = MyClass()
c = MyClass()

Is there any way to do this?

+3
source share
6 answers

you can have a list of names that you want to name objects, and then in a loop you add names to the global namespace when creating and object names.

list_of_names = ['a', 'b', 'c', 'd']
for name in list_of_names:
    globals()[name] = your_object()

People here will definitely say that this is a bad way to code without any compelling reason, but it will directly solve your problem without any further lists or dict.

+1
source

; dict, , , .

,

a,b,c = (MyClass() for _ in range(3))
+8

You can do this using exec. See Also Changing Locales in Python

>>> class Foo(object): pass
... 
>>> for name in "abc":
...     exec "{0} = Foo()".format(name)
... 
>>> a
<__main__.Foo object at 0x10046a310>
>>> b
<__main__.Foo object at 0x10046a390>
>>> c
<__main__.Foo object at 0x10046a3d0>
+2
source

You can create a list containing all instances. For instance:

instances = [MyClass() for i in range(0, N)]
+1
source

Not easy, it's usually a bad idea to do something like this; someone can explain why, because it is not entirely clear to me.

Instead you can do

class MyClass(object):
    pass

list_of_insts = []
for i in something:
    #create an instance
    lists_of_insts.append(MyClass())

Then you can refer to each item in this list lists_of_insts[0]. You can also assign them dictinstead of a list for easier access.

0
source

How to save these variables in dict? how

variables = {}
varnames = ['a', 'b', 'c']
for i, something in enumerate(things):
    variables[varnames[i]] = MyClass()
0
source

All Articles