概念

装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。
总的来说,装饰器就是为在不增加函数代码量的情况下为函数或对象增加额外的功能。

装饰器的简单实现

Python使用@语法糖实现装饰器
无参数函数:

写法一(Python中函数也可以作为参数传递):

def debug(func):
  def wrapper():
      print "[DEBUG]: enter {}()".format(func.__name__)
      return func()
  return wrapper
def say_hello():
  print ("hello!")
say_hello=debug(say_hello)

写法二:

def debug(func):
  def wrapper():
      print "[DEBUG]: enter {}()".format(func.__name__)
      return func()
  return wrapper
@debug
def say_hello():
  print ("hello!")

被装饰函数需要传入参数,为了让装饰器适应性更强,使用可变参数args 和关键字可变参数 **kw:

def debug(func):
    def wrapper(*args, **kwargs):  
        print "[DEBUG]: enter {}()".format(func.__name__)
        print 'Prepare and say...',
        return func(*args, **kwargs)
    return wrapper  # 返回
@debug
def say(something):
    print "hello {}!".format(something)

参考来源:

https://www.cnblogs.com/cicaday/p/python-decorator.html