如何以编程方式在Python中添加实例?

G M*_*G M 2 python metaprogramming class

我想以instance's attributes 编程方式编译从外部(.csv)文件导入数据.到目前为止,我可以手动执行一个实例.使用此工作流程:

class RS: #the calss has the importer method and many attributes
   ... 
#workflow starts here
a=RS() #I create the instance
a.importer('pathofthefile') #the importer method fills the attributes of the instance with the exeternal file
#ends here and restart...
b=RS()
b.importer('path...
Run Code Online (Sandbox Code Playgroud)

我想以编程方式创建实例并填充它们importer.如何class在大量文件上迭代此过程?例如,listdir用于导入文件夹中的所有文件?我喜欢这样的东西来创建实例:

for i in 'abcd':
    eval('%s=RS()' %(i))
Run Code Online (Sandbox Code Playgroud)

但当然似乎不起作用..

Rem*_*ich 5

您不应该将它们读入具有不同名称的变量 - 您将如何使用变量?

而是将它们读入具有单个名称的数据结构中.

让我们把实例的实际过程和导入到函数中:

def read_instance(filename):
    instance = RS()
    instance.importer(filename)
    return instance
Run Code Online (Sandbox Code Playgroud)

然后你可以做一个列表:

instances = [read_instance(filename) for filename in 'abcd']

print len(instances)  # Prints 4
print instance[0]  # Prints the first
print instance[1]  # Prints the second, etc
Run Code Online (Sandbox Code Playgroud)

或者字典:

instances = {filename: read_instance(filename) for filename in 'abcd'}

print instances['c']  # Prints the instance corresponding to filename 'c'
Run Code Online (Sandbox Code Playgroud)