Python代码创建/实现字典时出错

时间:2013-09-20 16:41:25

标签: python

这是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'**

2 个答案:

答案 0 :(得分:2)

问题是init方法是__init__而不是_init_(请参阅前后的双下划线)。

def __init__(self, pword=[]):
    self.word = pword

答案 1 :(得分:1)

class dictionary:
    def _init_(self, pword=[]):
        self.word = pword

特殊方法的名称是__init__,每侧有两个下划线,而不只是一个。因此,这将导致不自动调用该方法,而不是初始化列表。

您可以使用内置字典来模拟“字典”:

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上呼叫nword时,您也可以随时添加密钥。然后,您甚至可以使用defaultdict使一切变得非常简单:

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