简体   繁体   English

Python高阶函数中的可变作用域

[英]Variable scope in Python higher-order functions

I am looking at some learning material here: http://anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators 我在这里查看一些学习资料: http : //anandology.com/python-practice-book/functional-programming.html#higher-order-functions-decorators

Particularly the Memoize section, in which the following code is used as an example for higher-order functions: 特别是“ Memoize部分,其中以下代码用作高阶函数的示例:

def memoize(f):
    cache = {}
    def g(x):
        if x not in cache:
            cache[x] = f(x)
        return cache[x]
    return g

It was my understanding that the function returned by memoize would not have access to the "cache" variable since it is out of scope of the definition of "g". 据我了解,memoize返回的函数将无法访问“缓存”变量,因为它超出了“ g”定义的范围。

Eg. 例如。 if I do result_function = memoize(some_function) that result_function would have no knowledge of any cache variable since it is declared outside the g function and the g function alone is returned. 如果我执行result_function = memoize(some_function) ,则result_function将不知道任何cache变量,因为它是在g函数外部声明的,并且仅返回g函数。 Why does it work, and not throw an error? 为什么有效,并且不会引发错误?

the def memoize(): line introduces a new scope. def memoize():行引入了一个新的作用域。 the g function code 'sees' the scope of its enclosing function. g功能代码“看到”其封闭功能的范围。 Sure do look into this question's answers: Short Description of the Scoping Rules? 确定要研究此问题的答案: 作用域规则的简短说明吗? .

So no: that's not an error! 否:这不是错误! It's a very nice feature. 这是一个非常好的功能。

the cache object and g(x) object both have the same scope as they are both objects in the memoize function. 缓存对象和g(x)对象都具有相同的作用域,因为它们都是备忘录功能中的对象。 This means that g(x) will have access to cache because they are both objects scoped in the memoize function. 这意味着g(x)将有权访问缓存,因为它们都是在备忘录功能中限定的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM