这里有 2 个程序,一个用于创建字典,另一个用于实现它,第一个是:-
class dictionary:
def _init_(self, pword=[]):
self.word = pword
def addWord(self, nword):
l = len(self.word)
bp = -1
for num in range(0,l):
if self.word[num][0]==nword:
return
if self.word[num][0]>nword:
bp = num
break
nl = [nword]
self.word.append([])
if bp>=0:
for num in range(l-1,bp+1,-1):
self.word[num] = self.word[num-1]
else:
bp+=1
(self.word).insert(bp,nl)
def addKey(self, nword,key):
l = len(self.word)
for num in self.word:
if num[0]==nword:
if num.count(key)==0:
num.append(key)
return
print("'"+nword+"' was not found in the present dictionary\n")
def display(self):
if len(self.word)==0:
print("Dictionary is currently Empty\n")
return
for num in self.word:
for nw in num:
print(nw+"\t")
print("\n")
另一个是
import file
def main():
print("Running file")
td = file.dictionary()
td.addWord("A")
td.addWord("B")
td.addWord("C")
print("Words added")
td.addKey("A",1)
td.addKey("A",2)
td.addKey("B",3)
td.addKey("C",1)
td.addKey("C",3)
print("Keys added")
td.display()
main()
两个程序都编译没有问题但是当我运行第二个程序时,我收到以下错误
Running file
Traceback (most recent call last):
File "E:\Documents\Information Retrieval\ptrial.py", line 17, in <module>
main()
File "E:\Documents\Information Retrieval\ptrial.py", line 5, in main
td.addWord("A")
File "E:\Documents\Information Retrieval\file.py", line 6, in addWord
l = len(self.word)
AttributeError: 'dictionary' object has no attribute 'word'**