【发布时间】:2019-09-03 00:34:05
【问题描述】:
我是一名尝试学习 python 的初学者程序员,我遇到了作用域这个话题。在执行最底层的代码时,我遇到了错误“没有找到非本地 var_name 的绑定”。有人能解释一下为什么 nonlocal 关键字无法“查看”中间函数并进入外部函数吗?
#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()
【问题讨论】: