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

 用释怀来成全悲伤_490_905_560 发布于 2023-02-05 10:29

我想以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...

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

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

但当然似乎不起作用..

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

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

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

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

    然后你可以做一个列表:

    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'
    

    2023-02-05 10:30 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有