【发布时间】:2020-01-06 23:01:30
【问题描述】:
我试图了解闭包在 Python 中是如何工作的,我发现了以下代码 sn-p:
def closure():
count = 0
def inner():
nonlocal count
count += 1
print(count)
return inner
start = closure()
start() # prints 1
start() # prints 2
start() # prints 3
我可以理解这段代码,因为在定义inner函数时,封闭范围有一个名为count的变量,值为0,内部函数将remember这个值
但是,如果我将count = 0 移动到内部函数下方,则代码变为:
def closure():
def inner():
nonlocal count
count += 1
print(count)
count = 0
return inner
start = closure()
start() # prints 1
start() # prints 2
start() # prints 3
令我惊讶的是,代码仍然可以正常工作,这让我很困惑。在定义inner 时,变量count 不存在于封闭范围内,inner 函数如何能够记住此时命名空间中不存在的值?
是不是因为Python中也存在类似JS的变量hoisting的东西?
【问题讨论】:
标签: python scope namespaces closures