【问题标题】:python scoping - child scope should have access to parent scope?python 作用域 - 子作用域应该有权访问父作用域?
【发布时间】:2020-04-22 07:51:25
【问题描述】:

从我读到的here 来看,子作用域应该可以访问在父作用域中定义的变量。但是,就我而言,我在count 上遇到了一个未解决的错误。为什么会发生这种情况?

def find_kth_largest_bst(root, k):
        count = 0
    def _find_kth_largest_bst(root, k):
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1 #unresolved error here??
        pass

【问题讨论】:

  • 请附上完整的错误信息
  • 错误以红色波浪线显示在计数下方,如unresolved reference count``

标签: python scope


【解决方案1】:

您可以使用nonlocal 关键字从父作用域访问变量。

def find_kth_largest_bst(root, k):
    count = 0
    def _find_kth_largest_bst(root, k):
        nonlocal count  # This will access count from parent scope
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1
        pass

【讨论】:

    【解决方案2】:

    您正在做的是使用内部函数,这与类继承不同。另一个非常相似的问题是这个:

    Python nested functions variable scoping

    从这个问题一个答案说:

    " 关于范围和命名空间的文档是这样说的:

    Python 的一个特殊之处在于——如果没有全局语句生效——对名称的赋值总是进入最内部的作用域。赋值不会复制数据——它们只是将名称绑定到对象。

    这意味着您可以使用globalnonlocal 语句解决您的错误

    def find_kth_largest_bst(root, k):
        global count
        count = 0
        def _find_kth_largest_bst(root, k):
            if not root:
                return None
    
            _find_kth_largest_bst(root.right, k)
            count += 1 #unresolved error here??
            pass
    

    这里的另一件事是count = 0 有双制表符,即 8 个空格,而它应该只有一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      相关资源
      最近更新 更多