Python闭包:函数内部定义的函数可以访问上面一级的变量吗?

时间:2017-08-20 16:00:28

标签: python function functional-programming garbage-collection decorator

我正在学习装饰器,我有一个问题。在这个装饰器函数git filter-branch --tree-filter \ 'test -d project/app && mv project/app . || echo "Nothing to do"' HEAD 中,定义并返回另一个函数,并将"替换"函数call_counter作为参数传递给装饰器函数。

func

完成此操作后,我们可以通过以下方式从任何功能外部访问def call_counter(func): def helper(*args, **kwargs): helper.calls += 1 return func(*args, **kwargs) helper.calls = 0 return helper

helper.calls

输出:

@call_counter
def addition(x, y):
    return x + y

print(addition.calls)
addition(1, 2)
print(addition.calls)

我的问题是,在0 1 函数被调用并退出后,helper.calls变量如何存在于内存中?据我了解,call_counter存在于helper.calls的记忆中。但是,如果在call_counter执行完成后可以访问变量,这似乎不太可能。

2 个答案:

答案 0 :(得分:1)

callshelper的一个属性,它会一直存在直到helper死亡,而helper不会死亡,因为正如你所说,它将会生存下去addition名称。

答案 1 :(得分:0)

call_counter函数每次使用名称helper调用时都会创建一个新对象(函数)。 call_counter函数返回新创建的对象。而且当装饰器工作时它基本上是这样的:

def addition(x,y):
    return x+y
addition = call_counter(addition)

所以现在返回的对象(以前称为helper的函数)存储在addition下。