【问题标题】:scope of variable within a function in pythonpython中函数内变量的范围
【发布时间】:2020-01-19 17:51:08
【问题描述】:

在尝试解决 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 global variable/scope confusion
  • 哪个变量受到影响,错误在哪一行?
  • 是的。谢谢你。您能否也让我知道是否有更好的方法来解决此类问题?我应该将目标作为参数发送给辅助函数还是其他东西?

标签: python


【解决方案1】:

要解决此问题,请使用 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 是一个局部变量。

看看this answer

【讨论】:

  • 虽然这可能会解决最初的问题,但总的来说,这似乎是一个糟糕的模式。更好的解决方案是让内部 helper 函数保持纯本地计数并将其作为函数的结果返回。然后外部函数将使用:total += helper(root, sum, sum)
猜你喜欢
  • 1970-01-01
  • 2013-07-08
  • 2013-10-12
  • 2012-06-06
  • 2013-03-12
  • 2022-07-07
  • 2012-10-04
  • 2016-10-26
  • 1970-01-01
相关资源
最近更新 更多