我知道,在大多数情况下,非局部和全局关键字允许内部函数访问外部函数的变量或全局变量。但我看到的典型闭包示例通常只嵌套到2个级别(例如,1个外部函数和1个内部函数(。我很好奇我们如何在嵌套的函数范围中访问第一个函数范围中的变量。我知道这种类型的编程并不经常出现,但我很好奇的答案是什么
请参阅下面的示例
def pseudo_global(): # layer 1 -- first outer function
a = "global"
def block(): # layer 2
def show_a(): # layer 3
nonlocal a # doesn't do anything here because "a" isn't defined in block() scope
# global a # commented out; nothing prints anyway because refers to global scope
print(a) # free variable error; how can I access layer 1's variable here in layer 3?
show_a()
a = "block"
show_a()
block()
pseudo_global()
nonlocal a
正是您所需要的。问题是你需要两个。您需要告诉block()
和show_a()
a
是非局部的。
nonlocal
的定义是使变量引用最近封闭范围中先前绑定的变量,不包括全局变量。
def pseudo_global(): # layer 1 -- first outer function
a = "global"
def block(): # layer 2
nonlocal a
def show_a(): # layer 3
nonlocal a
print(a)
a = "block"
show_a()
block()
pseudo_global()
global
block