脚本宝典收集整理的这篇文章主要介绍了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)
以上是脚本宝典为你收集整理的python 装饰器顺序全部内容,希望文章能够帮你解决python 装饰器顺序所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。