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)