运行文件时,它给出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 = minimum_common_ancestor(root,node1,node2)。此变量包含整数值,并且与方法名称冲突。尝试重命名该变量。您还必须进行另一个更改,以将根节点作为第一个参数传递。尝试result_1 = lca.least_common_ancestor(lca.root,1,3)。享受编码。