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")
裝飾器調用順序python
#!/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)
執行結果app
<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)code