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

2024-09-25 08:38:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有两个程序,一个用来创建字典,另一个用来实现它,第一个为:-你知道吗

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

Tags: inselffordictionaryifdefnumword
2条回答

问题是init方法是__init__,而不是_init_(请参见前后双下划线)。你知道吗

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

特殊方法的名称是__init__,两边各有两个下划线,而不是一个下划线。因此,这将导致方法不会被自动调用,也不会初始化列表。你知道吗

您可以使用内置dict来模拟“dictionary”:

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,因为只要在一个还不存在的nword上调用addKey,您就可以动态添加键。您甚至可以使用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()

相关问题 更多 >