从类实例py2.7的字符串列表创建

时间:2012-02-04 18:36:52

标签: python oop list class instance

我的代码只创建最后一个实例len(list)如何更改它以分别创建每个实例? :|

 @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()

1 个答案:

答案 0 :(得分: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()