【问题标题】:Does Python closure require the outer scope going out of scope(i.e. ended)Python闭包是否需要外部范围超出范围(即结束)
【发布时间】: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 函数中。 helpervalues.sort(key=helper) 内部被调用。据我了解,sort_priority 的范围在到达values.sort(key=helper) 行时并没有结束。他为什么说这里发生了关闭?

我只是想知道 Brett 示例的闭包方面。我已经知道/了解sort_priorityhelper 的工作原理

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

【问题讨论】:

  • 我不担心这些事情。名字里有什么?任何其他名称的闭包都具有同样的功能。

标签: python python-3.x closures


【解决方案1】:

据我了解,sort_priority 的范围尚未结束 到达values.sort(key=helper) 行。他为什么说关闭 发生在这里?

假设这不是一个彻头彻尾的错误,斯拉特金肯定使用了不同的“闭包”定义。由于提供的代码是一个示例,我认为它附带了一个定义,您应该仔细比较一下您引用的代码。

我想 Slatkin 的想法围绕着 helper() 能够在 values.sort() 调用时访问周围上下文的 group 变量,其中该变量不在范围内。这至少类似于闭包的传统定义——该函数具有引用属于其定义上下文的数据的能力。我不认为我会同意它完全符合闭包的通常标准,但不要让这分散你对 Slatkin 试图教授的技术的本质的注意力。

【讨论】:

  • 按照这个例子,他陈述了 3 个原因:Python supports closures: functions that refer to variables from the scope in which they were defined. This is why the helper function is able to access the group argument to sort_priority.......This is why the return value from the helper closure causes the sort order to have two distinct groups.。它是Item 15: Know How Closures Interact with Variable Scope。 Pearson 在此处提供本书的示例页面:ptgmedia.pearsoncmg.com/images/9780134034287/samplepages/…
  • Brett 对该示例的跟进表明他的意思是关闭发生在helper,所以我认为他没有弄错。他的分析是深思熟虑的,但是这个闭包部分困扰着我,让我怀疑我对闭包的理解。我真的希望他对封闭的定义与其他人一致,因为我真的很喜欢他的书。感谢你的回答。我等了几天才能看到任何不同的见解。赞成:) +1
  • 所以,正如我所说:Slatkin 使用的闭包定义比您引用的更广泛,他在书中介绍了它。他指的是helper() 当从超出范围的地方调用变量时,能够从其定义的上下文中访问变量。我注意到这与the Wikipedia definition of the term 一致。恐怕同一个词被不同的人定义有点不同并不罕见。
猜你喜欢
  • 2013-05-09
  • 2013-11-01
  • 2016-04-13
  • 2012-12-15
  • 2014-01-13
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
相关资源
最近更新 更多