2011-10-05 96 views
1

我有一個從CSV文件導入數據的類以及一個使用文件名和輸出列表名稱的函數。我想使用setattr()函數將self.data_name的名稱設置爲self.info。我怎樣才能做到這一點?使用函數在類中設置列表名稱

import csv 

class import_data: 

    def import_csv(self, filename_csv, data_name): 


      setattr(self,data_name,0) 

      datafile = open(filename_csv, 'r') 
      datareader = csv.reader(datafile) 
      self.data_name = [] 

      for row in datareader: 
       self.data_name.append(row) 
      print("finished importing data") 

b = import_data() 
b.import_csv('info.csv', 'info') 
print(b.info) 

這不起作用,因爲b.data_nameb.info。這將打印0而不是導入的CSV文件。

回答

0

你將不得不更換self.data_name所有用法與調用要麼setattr()getattr()import_csv()功能能夠使用動態域名。

使用self.data_name將使用名爲data_name的成員,因爲我懷疑你已經意識到了,而這不是你想要做的。

例如,嘗試以下操作:

class import_data: 
    def import_csv(self, filename_csv, data_name): 

      #set dynamic named item to default value 
      #not required if this will happen anyway (in this example it does) 
      setattr(self,data_name,[]) 

      #preparation activities 
      datafile = open(filename_csv, 'r') 
      datareader = csv.reader(datafile) 

      #do required work using a temporary local variable 
      temp = [] 
      for row in datareader: 
       temp.append(row) 

      #copy the temporary local variable into the dynamically named one 
      setattr(self, data_name, temp) 

      #tidy up activities 
      datafile.close() 
      print("finished importing data") 

確保你看看eumiro的回答,使用withlist()這需要一個更好的,更緊湊,更Python的方法來您的具體問題。但是,上面應該很清楚地告訴你如何在更廣泛的情況下使用setattr()

+0

工作得非常好感謝 – Mandeep

2

試試這個:

class import_data: 
    def import_csv(self, filename_csv, data_name): 
     with open(filename_csv, 'r') as f: 
      setattr(self, data_name, list(csv.reader(f))) 
     print("finished importing data") 
+0

我認爲他想'b.data_name'是'b.info'和'b.info'是列表? – agf

+1

@agf - OP的最後兩個句子(代碼下方)說'b.info'應該包含CSV文件。我的代碼爲'b.import_csv('info.csv','info')' – eumiro

+0

+1,但是建議'newline ='''而不是'r''每個Python 3 [csv.reader](http ://docs.python.org/py3k/library/csv.html?highlight = csv#csv.reader)docs。 –