TypeError: 'dict' object is not callable from main

TypeError: 'dict' object is not callable from main

我编写了一个代码,用于存储文本文件中出现的单词并将其存储到字典中:

class callDict(object):
    def __init__(self):
        self.invertedIndex = {}

那我写个方法

def invertedIndex(self):
        print self.invertedIndex.items()

我是这样打电话的:

if __name__ == "__main__":
    c = callDict()
    c.invertedIndex()

但它给了我错误:

Traceback (most recent call last):
  File "E\Project\xyz.py", line 56, in <module>
    c.invertedIndex()
TypeError: 'dict' object is not callable

我该如何解决这个问题?

您正在代码中定义同名的方法和实例变量。这将导致名称冲突,从而导致错误。

更改一个或另一个的名称以解决此问题。

例如,这段代码应该适合您:

class CallDict(object):
    def __init__(self):
        self.inverted_index = {}
    def get_inverted_index_items(self):
        print self.inverted_index.items()

并使用以下方法检查:

>>> c = CallDict()
>>> c.get_inverted_index_items()
[]

另请查看 for doing this using @property 装饰器。

方法是 Python 中的属性,因此您不能在它们之间共享相同的名称。重命名其中之一。

除了回答,

@property
def invertedIndexItems(self):
    print self.invertedIndex.items()

那么你可以这样称呼它:

if __name__ == "__main__":
    c = callDict()
    print c.invertedIndexItems