2012-02-04 115 views
-1

我的代码只创建最后一个实例时间len(list)我如何改变这个来创建每个实例分离? :|从字符串列表创建类实例列表py2.7

@staticmethod 
def impWords(): 
    tempFile = open('import.txt','r+') 
    tempFile1 = re.findall(r'\w+', tempFile.read()) 
    tempFile.close() 

    for i in range(0,len(tempFile1)): 

     word.ID = i 
     word.data = tempFile1[i] 
     word.points = 0 
     Repo.words.append(word) 
     word.prt(word) 
    print str(Repo.words) 
    UI.Controller.adminMenu() 

回答

2

假设wordWord一个实例,你应该创建一个新的在每次迭代中,像这样:

@staticmethod 
def impWords(): 

    with open('import.txt','r+') as tempFile: 
     #re 
     tempFile1 = re.findall(r'\w+', tempFile.read()) 
     # using enumerate here is cleaner 
     for i, w in enumerate(tempFile1): 
      word = Word() # here you're creating a new Word instance for each item in tempFile1 
      word.ID = i 
      word.data = w 
      word.points = 0 
      Repo.words.append(word) 
      word.prt(word) # here it would be better to implement Word.__str__() and do print word 

    print Repo.words # print automatically calls __str__() 
    UI.Controller.adminMenu() 

现在,如果你Word__init__需要IDdatapoints作为参数,和Repo.words是一个列表,你可以减少到:

@staticmethod 
def impWords(): 

    with open('import.txt','r+') as tempFile: 
     #re 
     tempFile1 = re.findall(r'\w+', tempFile.read()) 
     # using enumerate here is cleaner 
     Repo.words.extend(Word(i, w, 0) for i, w in enumerate(tempFile1)) 

    print Repo.words # print automatically calls __str__() 
    UI.Controller.adminMenu() 
+0

从以前的评论[他的班级](http://stackoverflow.com/questions/9141883/convert-string-elements-to-class-attributes-py-2-7#comment11492731_9141905)需要身份证,数据和点它的'__init__'。 – DSM 2012-02-04 18:45:36

+0

@DSM没有注意到它是一个双 – soulcheck 2012-02-04 18:51:44