[url=http://stackoverflow.com/questions/233673/lexical-closures-in-python]http://stackoverflow.com/questions/233673/lexical-closures-in-python[/url])
另外的两个用途local caches/memoization
def calculate(a, b, c, memo={}):
try:
value = memo[a, b, c] # return already calculated value
except KeyError:
value = heavy_calculation(a, b, c)
memo[a, b, c] = value # update the memo dictionary
return value
(对一些递归算法非常好用)
对高度优化的代码而言, 会使用局部变量绑全局的变量:
import math
def this_one_must_be_fast(x, sin=math.sin, cos=math.cos):
...
[b]这是如何工作的?[/b]
当Python执行一条def语句时, 它会使用已经准备好的东西(包括函数的代码对象和函数的上下文属性),创建了一个新的函数对象。同时,计算了函数的默认参数值。
不同的组件像函数对象的属性一样可以使用。上文用到的'function'
>>> function.func_name
'function'
>>> function.func_code
<code object function at 00BEC770, file "<stdin>", line 1>
>>> function.func_defaults
([1, 1, 1],)
>>> function.func_globals
{'function': <function function at 0x00BF1C30>,
'__builtins__': <module '__builtin__' (built-in)>,
'__name__': '__main__', '__doc__': None}
这样你可以访问默认参数,你甚至可以修改它。
>>> function.func_defaults[0][:] = []
>>> function()
[1]
>>> function.func_defaults
([1],)
然而我不推荐你平时这么使用。
另一个重置默认参数的方法是重新执行相同的def语句,Python将会和代码对象创建一个新的函数对象,并计算默认参数,并且把新创建的函数对象赋值给了和上次相同的变量。但是再次强调,只有你清晰地知道在做什么的情况下你才能这么做。
And yes, if you happen to have the pieces but not the function, you can use the function class in the new module to create your own function object.