从文件读取并根据文件输入实例化新类
我正在尝试存储一个对类的 id 进行编码的文件,读取该文件并调用该类,以便 -> 在文件中,数据将被存储,
id_class:(arguments)
就像读取的文件将从文件列表中查找正确的类来调用并传递参数一样。
像这样的东西:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我更改了两个
create
方法 - 它们缺少括号,没有它们就不会创建对象的新实例。另外,我更改了class_dict
,因此它不会调用create
方法,而是将实例化推迟到访问class_dict
时:class_dict[索引]()
。修改后的代码如下所示:I changed both
create
methods - they were missing parenthesis, without them no new instances of the object were created. Also, I changed theclass_dict
so it won't call thecreate
methods, instead I defer the instantiation to the moment theclass_dict
is accessed:class_dict[index]()
. The modified code looks like this: