【发布时间】:2019-12-28 21:52:20
【问题描述】:
如this SO answer A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution 中所述。据我了解,函数范围在返回时已完成。几本关于 python 闭包的书总是有关于闭包定义嵌套函数并在末尾返回它以表示外部范围的结束的示例。比如Fluent Python by Ramalho
def make_averager():
series = []
def averager(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return averager
卢巴诺维奇的书Introducing Python
def knights2(saying):
def inner2():
return "We are the knights who say: '%s'" % saying
return inner2
然后我偶然发现了 Brett Slatkin 的书 Effective Python。他的闭包例子:
def sort_priority(values, group):
def helper(x):
if x in group:
return (0, x)
return (1, x)
values.sort(key=helper)
numbers = [8, 3, 1, 2, 5, 4, 7, 6]
group = {2, 3, 5, 7}
sort_priority(numbers, group)
Brett 说关闭发生在 helper 函数中。 helper 在 values.sort(key=helper) 内部被调用。据我了解,sort_priority 的范围在到达values.sort(key=helper) 行时并没有结束。他为什么说这里发生了关闭?
我只是想知道 Brett 示例的闭包方面。我已经知道/了解sort_priority 和helper 的工作原理
Pearson 提供 the sample pages of the book here。幸运的是,示例页面包含我提到的部分。是Item 15: Know How Closures Interact with Variable Scope
【问题讨论】:
-
我不担心这些事情。名字里有什么?任何其他名称的闭包都具有同样的功能。
标签: python python-3.x closures