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

2024-10-01 09:39:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码只创建最后一个实例乘以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()

Tags: 实例代码importtxtlendefrepoopen
1条回答
网友
1楼 · 发布于 2024-10-01 09:39:49

假设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()

相关问题 更多 >