I’m trying to store a file which encode an id of a class, read the file and call the class so that ->
in the files the data will be stored like
id_class:(arguments)
than the read file will look up from a list of file the right class to invoque and pass the arguments.
something like this:
class foo:
id = 1
def __init__(self):
self.attr = 10
def __str__(self):
return str(self.attr)
class bar:
id = 2
def __init__(self):
self.attr = 20
def __str__(self):
return str(self.attr)
def create_foo():
return foo
def create_bar():
return bar
class_dict = {1:create_foo(),2:create_bar()}
class_index = [1,2,1,2,1,1,1,2,2,2,1] #data read from file
class_list = [] #output list containing the newly instanciated bar or foo
for index in class_index:
c = class_dict[index]
class_list.append(c)
but this code append in the class_list for example foo, but is only one class, because if I modify the attribute will be modified in the whole list.
for example:
for classe in class_list:
print classe,
print "\n-------------"
class_list[0].attr = 15
for classe in class_list:
print classe,
the output is:
10 20 10 20 10 10 10 20 20 20 10
-------------
15 20 15 20 15 15 15 20 20 20 15
and should be:
10 20 10 20 10 10 10 20 20 20 10
-------------
15 20 10 20 10 10 10 20 20 20 10
I changed both
createmethods – they were missing parenthesis, without them no new instances of the object were created. Also, I changed theclass_dictso it won’t call thecreatemethods, instead I defer the instantiation to the moment theclass_dictis accessed:class_dict[index](). The modified code looks like this: