2011-10-24 38 views
1

我试图存储一个文件,它对一个类的id进行编码,读取文件并调用该类,以便在数据将被存储的文件中 - > 像基于文件输入从文件和instanciate新类读取

id_class:(arguments) 

比读文件会从文件列表中查找正确的类来invoque并传递参数。

是这样的:

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) 

但是这个代码附加在class_list例如FOO,但只有一个班,因为如果我修改的属性将在整个列表进行修改。

例如:

for classe in class_list: 
    print classe, 

print "\n-------------" 
class_list[0].attr = 15 

for classe in class_list: 
    print classe, 

输出为:

10 20 10 20 10 10 10 20 20 20 10 
------------- 
15 20 15 20 15 15 15 20 20 20 15 

,应该是:

10 20 10 20 10 10 10 20 20 20 10 
------------- 
15 20 10 20 10 10 10 20 20 20 10 

回答

1

我都修改了create方法 - 他们失踪括号,没有他们不该对象的新实例已创建。此外,我更改了class_dict,因此它不会调用create方法,而是将实例化推迟到访问class_dict时:class_dict[index]()。修改后的代码如下所示:

class foo: 
    id = 1 
    def __init__(self): 
     self.attr = 10 

class bar: 
    id = 2 
    def __init__(self): 
     self.attr = 20 

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) 

for classe in class_list: 
    print str(classe.attr), 

print "\n-------------" 
class_list[0].attr = 15 

for classe in class_list: 
    print str(classe.attr), 
+0

python的魔力!它工作...但为什么? – Pella86

+0

那里,我只是解释了变化:) –

+0

谢谢你,我问自己如何instanciate一个新的对象;) – Pella86