转:如何更通俗地讲解Python的装饰器?
本文参考:
廖雪峰:装饰器 (推荐)
装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于插入日志、性能测试、事务处理、缓存、权限校验等场景。
示例1:简单装饰器
import logging def use_logging(func): def wrapper(): logging.warning('{} is running'.format(func.__name__)) return func() # 把foo当做参数传递进来时,执行func()就相当于执行foo() return wrapper def foo(): print('i am foo') ff = use_logging(foo) # 因为装饰器use_logging(foo)返回的是函数对象wrapper,这条语句相当于ff=wrapper ff() # 执行ff()就相当于执行wrapper()
示例2:语法糖
def use_logging(func): def wrapper(): logging.warn("%s is running" % func.__name__) return func() return wrapper @use_logging def foo(): print("i am foo") foo()
示例3:业务函数test带参数
def wrapper(name): logging.warn("%s is running" % func.__name__) return func(name) return wrapper @use_logging def foo(name): print("i am %s" % name)
def square_it(fn): def warp(*args): return fn(*args)**2 return warp @square_it def test(x): return x + 2 print(test(2))
示例4:带参数的装饰器
def use_logging(level): def decorator(func): def wrapper(*args, **kwargs): if level == "warn": logging.warn("%s is running" % func.__name__) elif level == "info": logging.info("%s is running" % func.__name__) return func(*args) return wrapper return decorator @use_logging(level="warn") def foo(name='foo'): print("i am %s" % name) foo()