无法理解如何在嵌套闭包中评估自由变量值?
我创建了一个嵌套闭包
,如下所示:
def incrementer(n):
def inner(start):
current = start
def inc():
nonlocal current
current += n
return current
return inc
return inner
fn = incrementer(2)
现在,当我打印fn
的co_freevars
值时,我得到以下输出:
print(fn.__code__.co_freevars) -> ('n',)
我的理解是它应该是()
,因为inner
内部直接没有没有自由变量
。
为什么 print(fn.__code__.co_freevars)
不打印 ()
?
I have created a nested closure
which looks as below:
def incrementer(n):
def inner(start):
current = start
def inc():
nonlocal current
current += n
return current
return inc
return inner
fn = incrementer(2)
Now, when I print value of co_freevars
for fn
I get below output:
print(fn.__code__.co_freevars) -> ('n',)
My understanding is that it should be ()
because there are no free variables
directly inside inner
.
Why print(fn.__code__.co_freevars)
is not printing ()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
想想
def inc
实际上在做什么:它正在创建一个 closure 对象,其中填充了对当前
和n
。为了让inner
(为其创建的闭包)能够做到这一点,它必须具有对n
本身的引用。Think about what
def inc
is actually doing: it’s creating a closure object populated with references (cells) tocurrent
andn
. For (a closure created for)inner
to be able to do that, it must have a reference ton
itself.