如this SO answerA closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution
所述。据我所知,函数作用域返回时已完成。有几本关于python闭包的书总是有闭包定义嵌套函数并在末尾返回它以表示外部作用域结束的例子。比如拉玛略的Fluent Python
def make_averager():
series = []
def averager(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return averager
卢巴诺维奇著
def knights2(saying):
def inner2():
return "We are the knights who say: '%s'" % saying
return inner2
然后我偶然发现了布雷特·斯拉特金的书。他的结案例子:
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)
行时还没有结束。他为什么说这里发生了结?你知道吗
我只想知道布雷特例子的结尾部分。我已经知道/理解了sort_priority
和helper
的工作原理
皮尔逊提供 the sample pages of the book here。幸运的是,示例页面有我提到的部分。它是Item 15: Know How Closures Interact with Variable Scope
假设这不是一个彻头彻尾的错误,斯莱特金必须使用不同的定义“关闭”。由于给出的代码是一个示例,因此我假定它附带了一个定义,您应该仔细地将其与引用的定义进行比较。你知道吗
我假设Slatkin的想法是围绕着
helper()
,当values.sort()
调用周围上下文的group
变量时,该变量不在作用域中。这至少类似于闭包的常规定义,函数具有引用属于其定义上下文的数据的能力。我不认为我会同意,它完全符合通常的标准关闭,但不要让你从本质上的技术,斯莱特金是试图教分心。你知道吗相关问题 更多 >
编程相关推荐