本文参考:
装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于插入日志、性能测试、事务处理、缓存、权限校验等场景。
示例1:简单装饰器
def use_logging(func): def wrapper(): logging.warn("%s is running" % func.__name__) return func() # 把 foo 当做参数传递进来时,执行func()就相当于执行foo() return wrapper def foo(): print('i am foo') foo = use_logging(foo) # 因为装饰器 use_logging(foo) 返回的时函数对象 wrapper,这条语句相当于 foo = wrapper foo() # 执行foo()就相当于执行 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()