首页 > 解决方案 > Python - 'int' 对象不可调用

问题描述

我正在编写一个单链表,用于计算从测试文件中导入的单词数。我在课堂上初始化了计数。我定义了 print 函数,在它们被排序后打印出每个节点。我定义了一个计数类来遍历列表并计算输入给它的单词的所有出现次数。

我想将每个节点传递给计数,以计算它在我的文本文件中出现的次数。当我尝试这样做时,我最终得到 'int' object is not callable。这是我的代码

class Linked_List:
    def __init__(self):
        self.head = None
        self.count = 1

    def print(self):
        p = self.head
        head = Linked_List_node(p.data)
        while p is not None:
            print(p.data, '-', self.count(p.data)) # This is where the error appears
            p = p.next

    def count(self, x):
        # loop thru list for all x, if find x add 1 to count. Assign final count to that word.
        with open('cleaned_test.txt', 'r') as f:
            for line in f:
                for word in line.split():
                    if word == x:
                        self.count += 1

    def insert(self, x):
        """"""
        p = self.head
        q = None
        done = False
        while not done:
            if self.head == x:
                done = True

            elif p == None:
                head = Linked_List_node(x)
                q.next = head
                done = True

            elif x == p.data:
                #head = Linked_List_node(x)

                #head.counter += 1
                done = True

            elif x < p.data:
                if self.head == p:
                    head = Linked_List_node(x)
                    head.next = p
                    self.head = head
                    done = True
                else:
                    head = Linked_List_node(x)
                    head.next = p
                    q.next = head
                    done = True
            q = p
            if p is not None:
                p = p.next
class Linked_List_node:
    def __init__(self, value):
        self.data = value
        self.next = None

标签: python-3.x

解决方案


您的代码中的相关部分是:

class Linked_List:
    def __init__(self):
        # ...
        self.count = 1

    def count(self, x):
        # ...

self.count = 1赋值会覆盖创建self.count的每个Linked_List对象的值,因此它引用而1不是您在类上定义的方法。重命名变量或函数。


推荐阅读