Reputation: 313
I'd like to create instances of classes getting their names from list values or dictionaries keys or values. Basically what I'd like to do is:
iter = ['foo', 'bar']
for a in iter:
a = Cls()
and get foo and bar instances of Cls() class instead of having instance referenced by a updated at each loop.
Thanks in advance.
Upvotes: 0
Views: 154
Reputation: 9364
You could use dynamic code evaluation.
inst1 = eval("foo()")
inst2 = eval(a + "()")
inst3 = eval(a)()
Upvotes: -1
Reputation: 80761
Maybe with a dictionnary :
iter = ['foo', 'bar']
result = {}
for a in iter:
result[a] = Cls()
And in result you'll have { 'foo' : instance_of_Cls, 'bar' : instance_of_Cls}
Upvotes: 7