【问题标题】:How to programmatically add instances in Python?如何以编程方式在 Python 中添加实例?
【发布时间】:2014-01-26 18:50:20
【问题描述】:

我想编译 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))

但当然似乎不起作用..

【问题讨论】:

    标签: python class metaprogramming


    【解决方案1】:

    首先,eval 只处理表达式。要使用语句,您应该使用exec:

    >>>exec 'print 1'
    1
    

    但这不是最好的方法。你 cat 使用 globals 来访问和更改你的全局变量:

    >>>globals()['b'] = 1
    >>>b
    1
    

    所以解决方案可能如下所示:

    for var_name in 'abcd':
        globals()[var_name] = RS()
        globals()[var_name].importer('...
    

    【讨论】:

      【解决方案2】:

      这是我想做的,使用 globals() 内置:

      for i in 'abcd':
         globals()[i] = RS()
         globals()[i].importer('pathofthefile')
      

      为 Alexander 的回答添加一些不同的东西 :) 我想强调这种方法不适用于 locals(),它应该只用于读取变量而不是设置它们。

      【讨论】:

      • 操作。几乎是亚历山大的复制品。
      • 发生这种情况)。我也无意中复制了您的帖子,对此深表歉意。
      【解决方案3】:

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

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

      让我们把制作实例并导入函数的实际过程:

      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'
      

      【讨论】:

      • +1 我相信这是最好的答案(也解决了我和亚历山大之间令人尴尬的重复问题):)
      • 当然。我的回答只是为了展示如何使用元编程。 Ofc,正确的解决方案是上面的。
      • 是的,非常聪明,这解决了两个问题,我想问另一个问题来了解如何检索创建的所有实例的列表,但现在我不再需要它了......
      猜你喜欢
      • 2014-01-26
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2017-02-25
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多