gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:37:54 25 4
gpt4 key购买 nike

根据我读到的here ,子作用域应该有权访问父作用域中定义的变量。但是,就我而言,我在 count 上遇到了 Unresolved 错误。发生这种情况有什么原因吗?

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

最佳答案

您可以使用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 作用域 - 子作用域应该有权访问父作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59583819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com