Python闭包是否要求外部范围超出范围(即结束)

2024-10-01 09:37:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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函数中。helpervalues.sort(key=helper)内部被调用。据我所知,sort_priority的范围在到达values.sort(key=helper)行时还没有结束。他为什么说这里发生了结?你知道吗

我只想知道布雷特例子的结尾部分。我已经知道/理解了sort_priorityhelper的工作原理

皮尔逊提供 the sample pages of the book here。幸运的是,示例页面有我提到的部分。它是Item 15: Know How Closures Interact with Variable Scope


Tags: thekey函数helperreturndefgroupsort
1条回答
网友
1楼 · 发布于 2024-10-01 09:37:01

As I understand the scope of sort_priority has not ended when it reaches to the line values.sort(key=helper). Why does he say closure occurring here?

假设这不是一个彻头彻尾的错误,斯莱特金必须使用不同的定义“关闭”。由于给出的代码是一个示例,因此我假定它附带了一个定义,您应该仔细地将其与引用的定义进行比较。你知道吗

我假设Slatkin的想法是围绕着helper(),当values.sort()调用周围上下文的group变量时,该变量不在作用域中。这至少类似于闭包的常规定义,函数具有引用属于其定义上下文的数据的能力。我不认为我会同意,它完全符合通常的标准关闭,但不要让你从本质上的技术,斯莱特金是试图教分心。你知道吗

相关问题 更多 >