引用函数外的变量python

我正在编写一个 Python 函数来查找二叉树中所有节点的总和,只需使用中序遍历即可,如下所示:

sum=0
def tree_sum(root):
    if root!=None:
        tree_sum(root.left)
        sum=sum+root.data
        tree_sum(root.right)

虽然我收到以下错误:

sum=sum+root.data
UnboundLocalError: local variable 'sum' referenced before assignment

在这种情况下,我无法引用变量 sum 有什么原因吗?我在 Jupyter 笔记本中做了类似的事情(以这种方式引用变量)并且它有效。

回答

首先,不要命名您的变量sum,因为它会影的sum中内置。我会用node_sum.

您的第一个node_sum是在顶层声明的,因此它是一个全局变量。也就是说,如果不使用global函数内部的关键字,就无法更改全局变量:

node_sum = 0

def tree_sum(root):
    # Allow the global `node_sum` to be mutated inside this function
    global node_sum

    if root != None:
        tree_sum(root.left)
        node_sum = node_sum + root.data
        tree_sum(root.right)
node_sum = 0

def tree_sum(root):
    # Allow the global `node_sum` to be mutated inside this function
    global node_sum

    if root != None:
        tree_sum(root.left)
        node_sum = node_sum + root.data
        tree_sum(root.right)

但是,更好的做法是根本没有任何全局变量。使您的tree_sum函数返回当前树的总和,并将其添加到局部变量中node_sum

然后你可以像这样使用它

root = ...
print(tree_sum(root))


以上是引用函数外的变量python的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>