我的代码只创建最后一个实例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()
答案 0 :(得分:2)
假设word
是Word
的实例,您应该在每次迭代中创建一个新实例,如下所示:
@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
,data
和points
作为参数,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()