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

标签 python class metaprogramming

我想编译实例的属性,以编程方式从外部 (.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...

我想以编程方式创建实例,并用 classimporter 填充它们。如何在大量文件上重复此过程?例如使用 listdir 从文件夹导入所有文件? 我虽然是这样创建实例的:

for i in 'abcd':
    eval('%s=RS()' %(i))

但当然似乎不起作用..

最佳答案

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

相反,将它们读入具有单个名称的数据结构

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

def read_instance(filename):
    instance = RS()
    instance.importer(filename)
    return instance

然后你可以列一个 list :

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

或者字典:

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

print instances['c']  # Prints the instance corresponding to filename 'c'

关于python - 如何以编程方式在 Python 中添加实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999571/

相关文章:

python - Bash/python/perl 神奇地获取多个日志文件中的聚合日期时间

python - 如何在Python中使用filedialog将DataFrame保存到Excel文件?

c++ - 我应该更喜欢通过嵌套的 typedef 还是继承来调用模板元函数?

java - 如何从Android中的其他类而不是Activity调用Activity中的方法?

c# - 如何使用 System.Linq.Expressions API 模拟 "typeof (T)"?

ruby - 重新定义方法

python - 冒泡排序已经排序的列表

python - 如何在不保存图像的情况下将 PIL Image 对象上传到 Discord 聊天?

java - 初级 Java - 类编译器错误

C++ 获取对象