面试题编程题15-python 装饰器简单实例
from time import sleep import time #python装饰器库 - functools from functools import wraps #装饰普通函数 def decorator(fun): @wraps(fun) def wrapper(): start_time=time.time() fun() end_time=time.time() print(end_time-start_time) return wrapper @decorator def func(): sleep(1) #如上所示,有了 @ ,我们就可以省去func = decorator(func)这一句了,直接调用 func() 即可得到想要的结果。你们看到了没有,func() 函数不需要做任何修改,只需在定义的地方加上装饰器 func() func=decorator(func)# 因为装饰器 decorator(func) 返回的时函数对象 wrapper,这条语句相当于 func = wrapper func()# 执行foo()就相当于执行 wrapper() #这里的函数被wrapper替代了。它重写了我们函数的名字和注释文档(docstring)。幸运的是Python提供给我们一个简单的函数来解决这个问题,那就是functools.wraps。我们修改上一个例子来使用functools.wraps print('Steve '+func.__name__) #装饰类方法,带参数self def decorator1(fun): def wrapper(number): start_time = time.time() fun(number) end_time = time.time() print(end_time - start_time) return wrapper class Example(): @decorator1 def func(self): sleep(1) Example().func() #类装饰器 class Decorator(): def __init__(self,f): self.f=f def __call__(self, *args, **kwargs): print('start decoration!') self.f() print('enf decoration!') @Decorator def func(): print('func()') func() #装饰器链(多个装饰器) def decorator1(fun): @wraps(fun) def wrapper(): print('decotator1!') fun() return wrapper def decorator2(fun): @wraps(fun) def wrapper(): print('decotator2!') fun() return wrapper @decorator2 @decorator1 def func(): print('func()!') func()
想要了解更多,详见如下链接作者所写文章:
https://www.runoob.com/w3cnote/python-func-decorators.html
https://www.cnblogs.com/lianyingteng/p/7743876.html