Python Unit test for least common ancestor gives TypeError: 'int' object is not callable

Python Unit test for least common ancestor gives TypeError: 'int' object is not callable

当 运行 文件时,它给出 TypeError: 'int' 对象不可调用 。我只是在 python 学习单元测试。无法弄清楚我的原因和问题是什么?

文件lca.py

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

def least_common_ancestor(root=root, n1=1, n2=1):
    if root.value == n1 or root.value == n2:
        return root.value

    left = least_common_ancestor(root.left, n1, n2)
    right = least_common_ancestor(root.right, n1, n2)

    if left and right:
        return root.value

    if left:
        return left
    else:
        return right

least_common_ancestor = least_common_ancestor(root, node1, node2)

文件unittest.py

import lca

class TaskTest(unittest.TestCase):
    def test_least_common_ancestor(self):
        result_1 = lca.least_common_ancestor(node1=1, node2=3)
        self.assertEqual(result_1, 3)

if __name__ == '__main__':
    unittest.main()

当 运行 unit_test.py:

时出现错误
..E
======================================================================
ERROR: test_least_common_ancestor (__main__.TaskTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/user/Desktop/learn_python/unit_test.py", line 5, in test_least_common_ancestor
    result_1 = lca.least_common_ancestor(node1=1, node2=3)
TypeError: 'int' object is not callable

问题出在这一行 least_common_ancestor = least_common_ancestor(root, node1, node2)。此变量包含整数值并与方法名称冲突。尝试重命名变量。 您必须需要将根节点作为第一个参数传递的另一个更改。试试 result_1=lca.least_common_ancestor(lca.root, 1, 3)。享受编码。