首页 > 解决方案 > python中函数内变量的范围

问题描述

在尝试解决 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
'''

标签: python

解决方案


要解决此问题,请使用nonlocal声明:

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是一个局部变量。

看看这个答案


推荐阅读