问题描述
我正在尝试中的问题中的一段代码。
I am trying a piece of code from the question in Lexical closures in Python
flist = []
for i in xrange(3):
def func(x): return x*i
flist.append(func)
for f in flist:
print f.func_closure
输出为:
None
None
None
不应该是?:
(<cell at 0x9222d94: int object at 0x8cabdbc>,)
(<cell at 0x9222d94: int object at 0x8cabdbc>,)
(<cell at 0x9222d94: int object at 0x8cabdbc>,)
我已经使用下面的代码:
I have got the above output using the following code:
flist = []
def actualFact():
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f.func_closure
我使用Python 2.6.6(r266:84292,2010年9月15日,15:52:39)。
I am using Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39).
推荐答案
只有在全局(模块)范围外引用变量时,才会引入闭包:
Closures are only introduced if there are variables to be referenced outside of the global (module) scope:
>>> def foo():
... def bar(): pass
... return bar
...
>>> foo().func_closure is None
True
>>> spam = 'eggs'
>>> def foo():
... def bar(): return spam
... return bar
...
>>> foo().func_closure is None
True
只有当内部函数引用变量在周围范围内产生闭包:
Only when the inner function refers to a variable in the surrounding scope are closures generated:
>>> def foo():
... spam = 'eggs'
... def bar(): return spam
... return bar
...
>>> foo().func_closure is None
False
>>> foo().func_closure
(<cell at 0x108472718: str object at 0x108471de0>,)
请注意,您实际上必须引用周围范围中的一个变量。只要忽略范围,您再次无
:
Note that you actually have to refer to a variable in the surrounding scope. Simply ignoring the scope gives you None
again:
>>> def foo():
... spam = 'eggs'
... def bar(): pass
... return bar
...
>>> foo().func_closure is None
True
在第一个示例中, i
是模块范围变量,只有在第二个示例中,您通过将代码包装在一个新函数中来引入一个新作用域 actualFact
。
In your first example, i
is a module-scope variable, only in your second example do you introduce a new scope by wrapping the code in a new function actualFact
.
这篇关于python闭合怪异的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!