【问题标题】:Create from list of strings list of class instances py2.7从类实例py2.7的字符串列表创建
【发布时间】:2012-02-26 22:31:53
【问题描述】:

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

【问题讨论】:

    标签: python oop list class instance


    【解决方案1】:

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

    【讨论】:

    • 来自之前的评论his class 在其__init__ 中获取id、数据和点。
    • @DSM 没有注意到它是双重的
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2015-07-22
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多