python装饰器的理解+顺序
2017-12-26 本文已影响0人
clshinem
def log(func):
def wrapper(*args,**kwargs):
return func(*args,**kwargs)
return wrapper
@log
def f():
···
相当于执行log(f)
如果有参数log('参数')(f)
=== wrapper(f)
def decorator_a(func):
print 'Get in decorator_a'
def inner_a(*args,**kwargs):
print 'Get in inner_a'
return func(*args,**kwargs)
return inner_a
def decorator_b(func):
print 'Get in decorator_b'
def inner_b(*args,**kwargs):
print 'Get in inner_b'
return func(*args,**kwargs)
return inner_b
@decorator_b
@decorator_a
def f(x):
print 'Get in f'
return x*2
f(1)
装饰器其实在定义的时候就执行了decorator_a
,decorator_b
(顺序为从下到上)所以会先打印出get in decorator_a
,和get in decoator_b
然后此时函数f已经变成了innerb
,===inner_b(inner_a(f))
当去调用f(1)
的时候,会打印出get in inner_a
,然后去调用inner_a
,打印出 get in inner_a
,然后调用f
打印出 get in f
,结束