python - Python 闭包是否需要外部作用域超出作用域(即结束)

标签 python python-3.x closures

this SO answer 中所述当函数可以从已完成其执行的封闭范围访问局部变量时,就会发生闭包。据我了解,函数作用域在返回时就完成了。几本关于 python 闭包的书籍总是有关于闭包的示例,定义一个嵌套函数并在最后返回它以表示外部作用域的结束。例如 Ramalho 的 Fluent Python

def make_averager():
    series = []
    def averager(new_value):
        series.append(new_value)
        total = sum(series)
        return total/len(series)
    return averager

书籍 Python 简介 作者:Lubanovic

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 函数中。 helpervalues.sort(key=helper) 内部被调用。据我了解,当到达 values.sort(key=helper) 行时,sort_priority 的范围尚未结束。为什么他说这里发生了关闭?

我只是想知道 Brett 示例的闭合方面。我已经知道/理解 sort_priorityhelper 如何工作

Pearson 提供 the sample pages of the book here 。幸运的是,示例页面有我提到的部分。这是第 15 项:了解闭包如何与变量作用域交互

最佳答案

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 变量),其中该变量不在范围内。这至少类似于闭包的传统定义——函数具有引用属于其定义上下文的数据的能力。我不认为我会同意它完全符合闭包的通常标准,但不要让它分散您对 Slatkin 试图教授的技术本质的注意力。

关于python - Python 闭包是否需要外部作用域超出作用域(即结束),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515157/

相关文章:

python - cpython 做了什么来帮助检测对象循环(引用计数)?

python - Django 迁移到 MySql

python - 运行本地 mlflow 服务器时出错

javascript - jquery 和 javascript 的闭包

python - 如何在 Django Rest 框架中设置 View

Python 报告实验室 RML。如何在两个页面上拆分表格行

python - 使用 r2pipe 进行多处理

python - 获取字符串数字前缀的最简洁方法

JavaScript 和私有(private)变量

c++ - C++11 中的 Lambda 函数变量