python 装饰器顺序
def logging(level): def wrapper(func): def inner_wrapper(*args, **kwargs): print "[{level}]: enter function {func}()".format( level=level, func=func.__name__) return func(*args, **kwargs) return inner_wrapper return wrapper @logging(level='INFO') def say(something): print "say {}!".format(something) # 如果没有使用@语法,等同于 # say = logging(level='INFO')(say) @logging(level='DEBUG') def do(something): print "do {}...".format(something) if __name__ == '__main__': say('hello') do("my work")
装饰器调用顺序
#!/usr/bin/env python # encoding: utf-8 def decorator_a(func): print 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 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)
执行结果
<function f at 0x100d4b6e0> Get in decorator_a <function inner_a at 0x100d4bde8> Get in decorator_b Get in inner_b Get in inner_a Get in f
f(1)等价于decorator_b(decorator_a(f))(1)
相关推荐
kkpiece 2020-03-25
FlySky 2020-10-16
FlySky 2020-09-29
bizercsdn 2020-09-17
python0 2020-08-16
chenzulong 2020-08-16
LULUBAO 2020-07-08
一叶不知秋 2020-06-28
yogoma 2020-06-14
周小董 2020-06-10
hongxiangping 2020-06-09
xmwang0 2020-06-08
JJandYY 2020-05-31
Andrewjdw 2020-05-27
wklken的笔记 2020-05-27
zhuquan0 2020-05-26
chongtianfeiyu 2020-05-20
cas的无名 2020-05-19