-1

这里有 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'**
4

2 回答 2

2

问题是 init 方法__init__不是_init_(参见前后双下划线)。

def __init__(self, pword=[]):
    self.word = pword
于 2013-09-20T16:44:05.547 回答
1
class dictionary:
    def _init_(self, pword=[]):
        self.word = pword

特殊方法的名称__init__每边有两个下划线,而不仅仅是一个。所以这将导致方法不会被自动调用,而不是初始化列表。

你可以使用内置的 dict 来模拟你的“字典”:

class Dictionary:
    def __init__(self):
        self.dict = {}

    def addWord (self, nword):
        if nword not in self.dict:
            self.dict[nword] = []

    def addKey (self, nword, key):
        if nword in self.dict:
            self.dict[nword].append(key)
            return
        print('{0} was not found in the present dictionary'.format(nword))

    def display (self):
        if self.dict == {}:
            print("Dictionary is currently Empty\n")
        else:
            for k, v in self.dict.items():
                print('\t'.join(map(str,v)))
                print()

不过,您实际上并不需要addWord,因为您也可以在调用尚不存在addKey的 a时即时添加密钥。nword然后,您甚至可以使用 adefaultdict使一切变得非常简单:

import collections
class Dictionary (collections.defaultdict):
     def __init__ (self):
         super().__init__(list)

     def display (self):
        for k, v in self.items():
            print('\t'.join(map(str,v)))
            print()

td = Dictionary()
td['A'].append(1)
td['A'].append(2)
td['B'].append(3)
td['C'].append(1)
td['C'].append(3)
td.display()
于 2013-09-20T16:44:53.493 回答