I'm a newbie to python and I think similar question have been asked (including this one: Can you use a string to instantiate a class in python?), but I don't understand the answers or how to apply them.
I'm trying to create multiple instances of a class using what i'll call 'instance names' in a list.
Here's an example of what I'm trying to do:
class InstanceNames():
def __init__(self):
self.names = ['inst1', 'inst2', 'inst3']
class DoSomething():
instances = []
def __init__(self):
DoSomething.instances.append(self)
instance_names = InstanceNames()
for x in range(len(instance_names.names)):
print x
# following line not working at creating instances of DoSomething
instance_names.names[x] = DoSomething()
print DoSomething.instances
I changed the list for loop, and now I'm getting the following output:
0
1
2
[<__main__.DoSomething instance at 0x10cedc3f8>, <__main__.DoSomething instance at 0x10cedc440>, <__main__.DoSomething instance at 0x10cedc488>]
did it work? I'm so confused i'm not sure.
Ok. This is some ugly code, but here's what I have now:
class InstanceNames():
def __init__(self):
self.i_names = {'inst1': None, 'inst2': None, 'inst3': None}
self.o_names = ['foo', 'bar', 'baz']
class DoSomething():
instances = []
def __init__(self, blah_blah):
DoSomething.instances.append(self)
self.name = blah_blah
def testy(self, a):
a = a * 2
instance_names = InstanceNames()
for x in range(len(instance_names.i_names)):
print x
instance_names.i_names[x] = DoSomething(instance_names.o_names[x])
print "\n"
print DoSomething.instances
print "\n"
for y in DoSomething.instances:
print y.name
print y.testy(4)
print "\n"
Here is my output:
0
1
2
[<__main__.DoSomething instance at 0x10dc6c560>, <__main__.DoSomething instance at 0x10dc6c5a8>, <__main__.DoSomething instance at 0x10dc6c5f0>]
foo
None
bar
None
baz
None
Why is the 'name' variable printing, but the 'testy' method is not?