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.
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}
You could use dynamic code evaluation.
inst1 = eval("foo()")
inst2 = eval(a + "()")
inst3 = eval(a)()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.