python中函数中变量的作用域

python中函数中变量的作用域,python,Python,在试图解决leetcode上的一个问题时,我遇到了一个错误“赋值前引用的局部变量”。下面我给出了完整的代码(代码本身的逻辑不是我的问题)。我已经在外部函数中定义了变量。我在某处读到,在python中,变量的作用域是这样工作的——首先在本地搜索变量,然后在外部函数(如果有)中搜索,然后是全局搜索。在我的代码中,不存在局部变量“total”,但在外部函数中定义了一个。我对变量范围的理解是否错误? 另外,我在另一个问题中使用了类似的东西,但我使用的不是整数,而是一个列表,它类似地仅在外部函数中定义,并

在试图解决leetcode上的一个问题时,我遇到了一个错误“赋值前引用的局部变量”。下面我给出了完整的代码(代码本身的逻辑不是我的问题)。我已经在外部函数中定义了变量。我在某处读到,在python中,变量的作用域是这样工作的——首先在本地搜索变量,然后在外部函数(如果有)中搜索,然后是全局搜索。在我的代码中,不存在局部变量“total”,但在外部函数中定义了一个。我对变量范围的理解是否错误? 另外,我在另一个问题中使用了类似的东西,但我使用的不是整数,而是一个列表,它类似地仅在外部函数中定义,并附加在内部函数中。在这种情况下,没有发生这样的错误。我做错了什么?如有任何澄清,我们将不胜感激

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        total = 0
        if root is None:
            return 0

        def helper(root, sum, rem):
            if root is None:
                return 


            if root.val == rem:
                total += 1

            if root.left is not None:
                helper(root.left, sum, sum - root.val)    

            if root.right is not None:
                helper(root.right, sum, sum - root.val)

            return 

        helper(root, sum, sum)

        return total
'''

要解决此问题,请使用
非本地
声明:

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> int:
        total = 0
        if root is None:
            return 0

        def helper(root, sum, rem):
            nonlocal total
            if root is None:
                return 


            if root.val == rem:
                total += 1

            if root.left is not None:
                helper(root.left, sum, sum - root.val)    

            if root.right is not None:
                helper(root.right, sum, sum - root.val)

            return 

        helper(root, sum, sum)

        return total
本质上,
total+=1
隐式地告诉Python
total
是一个局部变量


看看

这是否回答了您的问题?哪个变量受到影响,错误在哪一行?是的。非常感谢。你能告诉我有没有更好的方法来解决这类问题?我是否应该将target作为参数发送给helper函数或其他什么东西?虽然这可能会解决最初的问题,但总的来说,这似乎是一种不好的模式。更好的解决方案是,内部
helper
函数维护一个纯本地计数,并将其作为函数的结果返回。然后外部函数将使用:
total+=helper(root、sum、sum)