2012-02-04 6 views
-1

내 코드는 마지막 인스턴스 만 생성합니다. len (list) 어떻게 모든 인스턴스를 분리하여 만들 수 있습니까? : | wordWord의 인스턴스이라고 가정문자열 목록에서 만들기 클래스 인스턴스 목록 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

,이 같은 각 반복에서 새로 생성한다 : 이제

@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__는 매개 변수로 ID, datapoints 걸리는 경우 , 및 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)에서 ID, 데이터 및 포인트를 가져옵니다. 그것의'__init__'. – DSM

+0

@DSM은 그것이 두 배임을 알지 못했습니다. – soulcheck

관련 문제