根据我所读到的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发布于 2020-01-03 19:06:22
可以使用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发布于 2020-01-03 19:15:15
您要做的是使用内部函数,这与类继承不同。另一个非常相似的例子是:
Python nested functions variable scoping
从这个问题中,有一个回答是:
“有关Scopes和命名空间的文档说明如下:
Python的一个特殊特点是--如果没有有效的全局语句--名称的分配总是进入最内部的范围。赋值不复制数据--它们只是将名称绑定到对象。
这意味着您可以使用global或nonlocal语句解决错误。
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个空格,而它应该只有一个空格。
https://stackoverflow.com/questions/59583819
复制相似问题