所谓的装饰器,其实就是通过装饰器函数,来修改原函数的一些功能,使得原函数不需要修改。
函数装饰器
1.可以将函数赋值给变量,然后通过变量调用方法
2.可以将函数传给函数,然后进行调用
3.函数中可以声明函数,然后完成函数嵌套
4.函数也可以返回函数
def my_decorator(func):def wrapper():print('wrapper of decorator')func()return wrapperdef greet():print('hello world')test = my_decorator(greet)test()# 输出wrapper of decoratorhello worlddef my_decorator(func):def wrapper():print('wrapper of decorator')func()return wrapper@my_decoratordef greet():print('hello world')greet()# 多参的情况def my_decorator(func):def wrapper(*args, **kwargs):print('wrapper of decorator')func(*args, **kwargs)return wrapper
这段代码中,变量 greet 指向了内部函数 wrapper(),而内部函数 wrapper() 中又会调用原函数 greet(),因此,最后调用 greet() 时,就会先打印’wrapper of decorator’,然后输出’hello world’。
这里的函数 my_decorator() 就是一个装饰器,它把真正需要执行的函数 greet() 包裹在其中,并且改变了它的行为,但是原函数 greet() 不变。
多封装一层来接受自己的参数
def abc(num):def my_decorator(func):def wrapper():for i in range(num):print('wrapper of decorator')func()return wrapperreturn my_decorator@abc(4)def greet():print('hello world')greet()
当函数被装饰以后,它的元信息会发生更改
可以使用内部装饰器@functools.wrap,来保留之前的元信息
import functoolsdef my_decorator(func):@functools.wraps(func)def wrapper(*args, **kwargs):print('wrapper of decorator')func(*args, **kwargs)return wrapper@my_decoratordef greet(message):print(message)greet.__name__# 输出'greet'
类装饰器(就可以不用初始化对象了)
class Count:def __init__(self, func):self.func = funcself.num_calls = 0def __call__(self, *args, **kwargs):self.num_calls += 1print('num of calls is: {}'.format(self.num_calls))return self.func(*args, **kwargs)@Countdef example():print("hello world")example()# 输出num of calls is: 1hello worldexample()# 输出num of calls is: 2hello world...
嵌套装饰器
@decorator1@decorator2@decorator3def func():...
约等于:
decorator1(decorator2(decorator3(func)))
装饰器的作用:
1.中间件,在执行一段代码前,先去干什么
2.日志记录,计时器,装饰后可以检查某个函数的运行时间
import timeimport functoolsdef log_execution_time(func):@functools.wraps(func)def wrapper(*args, **kwargs):start = time.perf_counter()res = func(*args, **kwargs)end = time.perf_counter()print('{} took {} ms'.format(func.__name__, (end - start) * 1000))return resreturn wrapper@log_execution_timedef calculate_similarity(items):...
3.输入检查
4.缓存
