【问题标题】:Why do these decorator variables not get destroyed? [duplicate]为什么这些装饰器变量不会被破坏? [复制]
【发布时间】:2019-02-08 05:48:22
【问题描述】:

假设您有一个装饰器函数,该函数创建一个 dict 来存储出于性能原因已计算的结果。例如:

def memoize(func):

    cache = dict()

    def memoized_func(*args, **kwargs):
        if args in cache:
            return cache[args]

        result = func(*args)
        cache[args] = result
        return result

    return memoized_func

当我用myfunc = memoize(myfunc) 装饰一个函数时,我很难理解为什么会这样。

我最初认为缓存会在返回 memoized 函数后丢失,因为它超出了范围。我只会返回对装饰函数的引用。显然,事实并非如此。

谁能告诉我幕后发生了什么?

【问题讨论】:

  • 这就是闭包
  • 返回的函数作为对变量的引用,因此不会被垃圾回收。

标签: python python-3.x scope decorator python-decorators


【解决方案1】:

装饰器函数具有存储缓存的自身非本地范围。此范围在函数调用后不会破坏。更多信息https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 2011-12-05
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2012-07-24
    相关资源
    最近更新 更多