所谓的装饰器,其实就是通过装饰器函数,来修改原函数的一些功能,使得原函数不需要修改。

函数装饰器

1.可以将函数赋值给变量,然后通过变量调用方法
2.可以将函数传给函数,然后进行调用
3.函数中可以声明函数,然后完成函数嵌套
4.函数也可以返回函数

  1. def my_decorator(func):
  2. def wrapper():
  3. print('wrapper of decorator')
  4. func()
  5. return wrapper
  6. def greet():
  7. print('hello world')
  8. test = my_decorator(greet)
  9. test()
  10. # 输出
  11. wrapper of decorator
  12. hello world
  13. def my_decorator(func):
  14. def wrapper():
  15. print('wrapper of decorator')
  16. func()
  17. return wrapper
  18. @my_decorator
  19. def greet():
  20. print('hello world')
  21. greet()
  22. # 多参的情况
  23. def my_decorator(func):
  24. def wrapper(*args, **kwargs):
  25. print('wrapper of decorator')
  26. func(*args, **kwargs)
  27. return wrapper

这段代码中,变量 greet 指向了内部函数 wrapper(),而内部函数 wrapper() 中又会调用原函数 greet(),因此,最后调用 greet() 时,就会先打印’wrapper of decorator’,然后输出’hello world’。
这里的函数 my_decorator() 就是一个装饰器,它把真正需要执行的函数 greet() 包裹在其中,并且改变了它的行为,但是原函数 greet() 不变。

多封装一层来接受自己的参数

  1. def abc(num):
  2. def my_decorator(func):
  3. def wrapper():
  4. for i in range(num):
  5. print('wrapper of decorator')
  6. func()
  7. return wrapper
  8. return my_decorator
  9. @abc(4)
  10. def greet():
  11. print('hello world')
  12. greet()

当函数被装饰以后,它的元信息会发生更改
可以使用内部装饰器@functools.wrap,来保留之前的元信息

  1. import functools
  2. def my_decorator(func):
  3. @functools.wraps(func)
  4. def wrapper(*args, **kwargs):
  5. print('wrapper of decorator')
  6. func(*args, **kwargs)
  7. return wrapper
  8. @my_decorator
  9. def greet(message):
  10. print(message)
  11. greet.__name__
  12. # 输出
  13. 'greet'

类装饰器(就可以不用初始化对象了)

  1. class Count:
  2. def __init__(self, func):
  3. self.func = func
  4. self.num_calls = 0
  5. def __call__(self, *args, **kwargs):
  6. self.num_calls += 1
  7. print('num of calls is: {}'.format(self.num_calls))
  8. return self.func(*args, **kwargs)
  9. @Count
  10. def example():
  11. print("hello world")
  12. example()
  13. # 输出
  14. num of calls is: 1
  15. hello world
  16. example()
  17. # 输出
  18. num of calls is: 2
  19. hello world
  20. ...

嵌套装饰器

  1. @decorator1
  2. @decorator2
  3. @decorator3
  4. def func():
  5. ...

约等于:

  1. decorator1(decorator2(decorator3(func)))

装饰器的作用:

1.中间件,在执行一段代码前,先去干什么
2.日志记录,计时器,装饰后可以检查某个函数的运行时间

  1. import time
  2. import functools
  3. def log_execution_time(func):
  4. @functools.wraps(func)
  5. def wrapper(*args, **kwargs):
  6. start = time.perf_counter()
  7. res = func(*args, **kwargs)
  8. end = time.perf_counter()
  9. print('{} took {} ms'.format(func.__name__, (end - start) * 1000))
  10. return res
  11. return wrapper
  12. @log_execution_time
  13. def calculate_similarity(items):
  14. ...

3.输入检查
4.缓存