装饰器函数的执行顺序
2018-04-20 本文已影响0人
胖虎很可爱
先看一下代码:
from time import ctime, sleep
def outer(hre='chang'):
def timefun(func):
print(hre)
def wrappedfunc():
print("%s called at %s" % (func.__name__, ctime()))
func()
return wrappedfunc
return timefun
@outer('it')
def foo():
print("I am foo")
程序一次从上往下执行:
执行到def outer(hre='chang'):时,把这个函数注册到内存中,向下
执行到@outer('it')时,会找内存中def outer(hre='chang'):这个函数,返回值是timefun,此时变成了:
@timefun
def foo():
print("I am foo")
这就变成了普通的装饰器函数,然后会执行def timefun(foo): 返回值是wrappedfunc,相当于执行了
foo=timefun(foo),因为timefun(foo)返回值是wrappedfunc,所以执行foo()就相当于执行wrappedfunc().
内部函数wrappedfunc被引用,所以外部函数的一切变量均未被释放!!!