附录:关于装饰器

认识装饰器

在python中,对于一个函数,若想在其运行前后做点什么,那么装饰器是再好不过的选择,这种语法在一些项目中十分常见,是Python语言的黑魔法,用处颇多,话不多说,让我们看一下代码:

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 01.py
  4. __author__ = 'howie'
  5. from functools import wraps
  6. def decorator(func):
  7. @wraps(func)
  8. def wrapper(*args, **kwargs):
  9. print("%s was called" % func.__name__)
  10. func(*args, **kwargs)
  11. return wrapper
  12. @decorator
  13. def hello(name="howie"):
  14. print("Hello %s!" % name)
  15. hello()
  1. outputs:
  2. hello was called
  3. Hello howie!

这段代码,初看之下,确实不是很理解,接下来一步一步分析,看看装饰器到底是怎么工作的。

装饰器原理

在python中,方法允许作为参数传递,想在某个函数执行前后加点料,也可以这样简单实现。

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 02-1.py
  4. __author__ = 'howie'
  5. def decorator(func):
  6. print("%s was called" % func.__name__)
  7. func()
  8. def hello(name="howie"):
  9. print("Hello %s!" % name)
  10. decorator(hello)

由此,上面代码也可以这样写:

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 02-2.py
  4. __author__ = 'howie'
  5. def decorator(func):
  6. print("%s was called" % func.__name__)
  7. func()
  8. @decorator
  9. def hello(name="howie"):
  10. print("Hello %s!" % name)
  11. hello

两段代码执行后:

  1. outputs: shell
  2. hello was called
  3. Hello howie!

表面上看来,02-2.py代码看起来也可以很好地执行啊,可请注意,在末尾处,hello只是函数名称,它并不能被调用,若执行hello(),就会报TypeError: 'NoneType' object is not callable对象不能调用的错误,这是自然,因为在decoratorfunc()直接将传入的函数实例化了,有人会想,那如果这样改呢?

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 02-3.py
  4. __author__ = 'howie'
  5. def decorator(func):
  6. print("%s was called" % func.__name__)
  7. return func
  8. @decorator
  9. def hello(name="howie"):
  10. print("Hello %s!" % name)
  11. hello()

确实,这样改是可以,可有没有想过,若想在函数执行结束后加点装饰呢?这样便行不通了,可能又有人会想,若这样改呢?

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 02-4.py
  4. __author__ = 'howie'
  5. def decorator(func):
  6. print("%s was called" % func.__name__)
  7. func()
  8. return bye
  9. def bye():
  10. print("bye~")
  11. @decorator
  12. def hello(name="howie"):
  13. print("Hello %s!" % name)
  14. hello()

这样写看起来,恩,怎么说呢,总有种没有意义的感觉,不如直接将在外部的函数放进decorator中,如下:

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 02-5.py
  4. __author__ = 'howie'
  5. def decorator(func):
  6. def wrapper():
  7. print("%s was called" % func.__name__)
  8. func()
  9. print("bye~")
  10. return wrapper
  11. @decorator
  12. def hello(name="howie"):
  13. print("Hello %s!" % name)
  14. hello()

执行:

  1. outputs: shell
  2. hello was called
  3. Hello howie!
  4. bye~

怎么样,输出的结果是不是符合要求,其实简单来看的话,可以这样理解hello()==decorator(hello)()==wrapper(),最后其实就是执行wrapper()函数而已,事实就是如此的简单,不妨来验证一下:

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 02-6.py
  4. __author__ = 'howie'
  5. def decorator(func):
  6. def wrapper():
  7. print("%s was called" % func.__name__)
  8. func()
  9. print("bye~")
  10. return wrapper
  11. @decorator
  12. def hello(name="howie"):
  13. print("Hello %s!" % name)
  14. hello()
  15. print(hello.__name__)
  1. outputs: shell
  2. hello was called
  3. Hello howie!
  4. bye~
  5. wrapper

果然就是执行了wrapper函数,解决问题的同时也会出现新的问题,那便是代码中本来定义的hello函数岂不是被wrapper函数覆盖了,又该如何解决这个问题呢?这时候functions.wraps就可以登场了,代码如下:

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 02-7.py
  4. __author__ = 'howie'
  5. from functools import wraps
  6. def decorator(func):
  7. @wraps(func)
  8. def wrapper():
  9. print("%s was called" % func.__name__)
  10. func()
  11. print("bye~")
  12. return wrapper
  13. @decorator
  14. def hello(name="howie"):
  15. print("Hello %s!" % name)
  16. hello()
  17. print(hello.__name__)

执行代码:

  1. outputs: shell
  2. hello was called
  3. Hello howie!
  4. bye~
  5. hello

functions.wraps作用是不是一目了然哈~到了这一步,再看01.py的代码,是不是代码结构清晰明了,只不过多了个参数~

  1. #!/usr/bin/env
  2. # -*-coding:utf-8-*-
  3. # script: 01.py
  4. __author__ = 'howie'
  5. from functools import wraps
  6. def decorator(func):
  7. @wraps(func)
  8. def wrapper(*args, **kwargs):
  9. print("%s was called" % func.__name__)
  10. func(*args, **kwargs)
  11. return wrapper
  12. @decorator
  13. def hello(name="howie"):
  14. print("Hello %s!" % name)
  15. hello('world')

猜都猜得到执行后输出什么了。

结语

只要了解装饰器原理,不管是带参数的装饰器,还是装饰器类,都是小菜一碟。