python作用域的子作用域应该有权访问父作用域?

2024-09-27 04:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

从我读到的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

Tags: returnifhere定义defcount错误not
2条回答

您可以使用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

您所做的是使用内部函数,这与类继承不同。另一个非常类似的假设是:

Python nested functions variable scoping

这个问题的答案是:

" The documentation about Scopes and Namespaces says this:

A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects.

这意味着您可以用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个空格,而它应该只有一个

相关问题 更多 >

    热门问题