在步骤8,有一个定义为:
def outer(): x = 1 def inner(): print x # 1 return inner
如果我们运行它:
>>> foo = outer() >>> foo.func_closure # doctest: +ELLIPSIS
它不打印x.根据解释:
Everything works according to Python’s scoping rules – x is a local
variable in our function outer. When inner prints x at point #1 Python
looks for a local variable to inner and not finding it looks in the
enclosing scope which is the function outer,finding it there.But what about things from the point of view of variable lifetime? Our
variable x is local to the function outer which means it only exists
while the function outer is running. We aren’t able to call inner till
after the return of outer so according to our model of how Python
works,x shouldn’t exist anymore by the time we call inner and perhaps
a runtime error of some kind should occur.
但是,我真的不明白第二段是什么意思.
我理解inner()确实得到x的值,但为什么它不打印x?
谢谢
更新:
谢谢大家的答案.现在我明白了原因.
“return inner”只是一个指向inner()的指针,但它没有被执行,这就是为什么inner()不打印x,因为它根本没有被调用