从文件读取并基于文件输入实例化新类

时间:2011-10-24 01:34:42

标签: python file data-structures

我正在尝试存储一个编码类的id的文件,读取该文件并调用该类,以便 - > 在文件中,数据将像

一样存储
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 个答案:

答案 0 :(得分: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),