我编写了一个代码,用于存储文本文件中出现的单词并将其存储到字典中:
class callDict(object):
def __init__(self):
self.invertedIndex = {}
Run Code Online (Sandbox Code Playgroud)
然后我写了一个方法
def invertedIndex(self):
print self.invertedIndex.items()
Run Code Online (Sandbox Code Playgroud)
这就是我打电话的方式:
if __name__ == "__main__":
c = callDict()
c.invertedIndex()
Run Code Online (Sandbox Code Playgroud)
但它给了我错误:
Traceback (most recent call last):
File "E\Project\xyz.py", line 56, in <module>
c.invertedIndex()
TypeError: 'dict' object is not callable
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
您正在代码中定义一个方法和一个实例变量,两者都具有相同的名称.这将导致名称冲突,从而导致错误.
更改其中一个或另一个的名称以解决此问题.
例如,此代码应该适合您:
class CallDict(object):
def __init__(self):
self.inverted_index = {}
def get_inverted_index_items(self):
print self.inverted_index.items()
Run Code Online (Sandbox Code Playgroud)
并使用以下方法检查:
>>> c = CallDict()
>>> c.get_inverted_index_items()
[]
Run Code Online (Sandbox Code Playgroud)
还可以查看ozgur使用@property 装饰器执行此操作的答案.