我是一个试图学习python的初学者程序员,我遇到了范围这个话题。在执行最底层的代码时,我遇到了错误“找不到非本地var_name的绑定”。有人能解释为什么非局部关键字不能“查看”中间函数和外部函数吗
#this works
globe = 5
def outer():
globe = 10
def intermediate():
def inner():
nonlocal globe
globe = 20
print(globe)
inner()
print(globe)
intermediate()
print(globe)
outer()
globe = 5
def outer():
globe = 10
def intermediate():
global globe #but not when I do this
globe = 15
def inner():
nonlocal globe #I want this globe to reference 10, the value in outer()
globe = 20
print(globe)
inner()
print(globe)
intermediate()
print(globe)
outer()
包含
nonlocal
关键字的表达式将导致Python尝试在封闭的局部作用域中查找变量,直到它第一次遇到第一个指定的变量namenonlocal globe
表达式将查看intermediate
函数中是否有名为globe
的变量。但是,它将在global
范围内遇到它,因此它将假定它已到达模块范围并完成对它的搜索,而没有找到nonclocal
范围,因此出现异常通过在
intermediate
函数中声明global globe
,您基本上关闭了到达前面作用域中具有相同名称的任何nonlocal
变量的路径。您可以看看讨论here为什么“决定”用Python以这种方式实现如果要确保变量
globe
在或不在某个函数的局部范围内,可以使用dir()
函数,因为从Python docs:相关问题 更多 >
编程相关推荐