装饰器核心
概念
装饰器来自 Decorator
的直译。什么叫装饰,就是装点、提供一些额外的功能。在 python 中的装饰器则是提供了一些额外的功能。
装饰器本质上是一个Python函数(其实就是闭包),它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。
装饰器用于有以下场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。
v1.0版本解决
def fun1():print("使用功能1")print("日志记录")
def fun2():print("使用功能2")print("日志记录")
v2.0版本解决
def writeLog():print("日志纪录")
def fun1():print("使用功能1")writeLog()
def fun2():print("使用功能2")writeLog()
v3.0版本解决
def outfunc(func):def infunc():func()print("日志纪录")return infunc
def fun1():print("使用功能1")
def fun2():print("使用功能2")
fun1 = outfunc(fun1)
# 装饰器(闭包)
fun1()
v4.0版本解决,装饰器
def outfunc(func):def infunc():func()print("日志纪录")return infunc
@outfunc
def fun1():print("使用功能1")
@outfunc
def fun2():print("使用功能2")
fun1()
fun2()
修改变量名,见名知意
def mylog(func):def infunc():func()print("日志纪录")return infunc
@mylog
def fun1():print("使用功能1")
@mylog
def fun2():print("使用功能2")
fun1()
fun2()
增加参数处理,可以装饰任意多个参数的函数
def mylog(func):def infunc(*args,**kwargs):func(*args,**kwargs)print("日志纪录")return infunc
@mylog
def fun1():print("使用功能1")
@mylog
def fun2(a,b):print(f"使用功能2:{a},{b}")
fun1()
fun2(100,200)
装饰器本质上是一个Python函数(其实就是闭包),它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。
装饰器用于有以下场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。
多个装饰器_执行顺序
多个装饰器
有时候,我们需要多个装饰器修饰一个函数。比如:需要增加日志功能、增加执行效率测试功能。
装饰器函数的执行顺序是分为(被装饰函数)定义阶段和(被装饰函数)执行阶段的,装饰器函数在被装饰函数定义好后立即执行
- 在函数定义阶段:执行顺序是从最靠近函数的装饰器开始,自内而外的执行
- 在函数执行阶段:执行顺序由外而内,一层层执行
【示例】多个装饰器执行顺序
@mylog
@cost_time
# 函数定义阶段:
# 相当于:
# fun2 = cost_time(fun2)
# fun2 = mylog(fun2)
# 也相当于:
# fun2 = mylog(cost_time(fun2))
# 定义阶段:先执行cost_time函数,再执行mylog函数
def fun2():pass
#调用执行阶段
#先执行mylog的内部函数,再执行cost_time的内部函数
fun2()
【示例】增加日志和执行计时功能的装饰器
import time
def mylog(func):print("mylog start")def infunc():print("日志纪录 start")func()print("日志纪录 end")
print("mylog end")return infunc
def cost_time(func):print("cost time start")def infunc():print("开始计时..")start = time.time()func()end = time.time()print(f"耗费时间:{end-start}")return end-start
print("cost time end")return infunc
@mylog
@cost_time
# 相当于:
# fun2 = cost_time(fun2)
# fun2 = mylog(fun2)
# 也相当于:
# fun2 = mylog(cost_time(fun2))
def fun2():print("使用功能2")time.sleep(2)print("使用功能22")
fun2()
带参数的装饰器典型写法
【示例】带参数的装饰器
# coding=utf-8
# 带参数的装饰器的典型写法
def mylog(type):def decorator(func):def infunc(*args,**kwargs):if type=="文件":print("文件中:日志纪录")else:print("控制台:日志纪录")return func(*args,**kwargs)return infuncreturn decorator
@mylog("文件")
def fun2(a,b):print("使用功能2",a,b)
if __name__ == '__main__':fun2(100,200)
wraps装饰器
wraps装饰器
一个函数不止有他的执行语句,还有着 __name__
(函数名),__doc__
(说明文档)等属性,我们之前的例子会导致这些属性改变。
functool.wraps
可以将原函数对象的指定属性赋值给包装函数对象,默认有module、name、doc,或者通过参数选择。
【示例】wraps装饰器案例
# coding=utf-8
from functools import wraps
def mylog(func):@wraps(func)def infunc(*args,**kwargs):print("日志纪录...")print("函数文档:",func.__doc__)return func(*args,**kwargs)return infunc
@mylog # fun2 = mylog(fun2)
def fun2():"""强大的功能2"""print("使用功能2")
if __name__ == '__main__':fun2()print("函数文档--->",fun2.__doc__)"""
运算结果:
日志纪录...
函数文档: 强大的功能2
使用功能2
函数文档---> 强大的功能2
"""
回顾内置装饰器(propery、staticmethod、classmethod)
我们在面向对象学习时,学习过三种装饰器: property
、 staticmethod
、 classmethod
。
property装饰器
property
装饰器用于类中的函数,使得我们可以像访问属性一样来获取一个函数的返回值。
【示例】prperty装饰器的使用
class User:def __init__(self,name,month_salary):self.name = nameself.month_salary = month_salary
@propertydef year_salary(self):return int(self.month_salary)*12
if __name__ == '__main__':u1 = User("gaoqi","30000")print(u1.year_salary)
staticmethod装饰器
staticmethod
装饰器同样是用于类中的方法,这表示这个方法将会是一个静态方法,意味着该方法可以直接被调用无需实例化,但同样意味着它没有 self
参数,也无法访问实例化后的对象。
【示例】staticmethod装饰器的使用
class Person:
@staticmethoddef say_hello():print("hello world!")
if __name__ == '__main__':Person.say_hello()
classmethod装饰器
classmethod
这个方法是一个类方法。该方法无需实例化,没有 self
参数。相对于 staticmethod
的区别在于它会接收一个指向类本身的 cls
参数。
【示例】classmethod装饰器
class Person:
@classmethoddef say_hello(cls):print(f"我是{cls.__name__}")print("hello world!")
if __name__ == '__main__':Person.say_hello()
类装饰器
上面写的装饰器都是函数来完成的。我们用类也可以实现装饰器。
类能实现装饰器的功能, 是由于当我们调用一个对象时,实际上调用的是它的 __call__
方法。
【示例】调用对象,__call__
方法的使用
class Demo:def __call__(self):print('我是 Demo')
demo = Demo()
demo() # 直接调用对象,实质是调用了他的__call__()
【示例】类装饰器的使用案例
class MyLogDecorator():def __init__(self,func):self.func = func
def __call__(self, *args, **kwargs):print("日志纪录...")return self.func(*args,**kwargs)
@MyLogDecorator
def fun2():print("使用功能2")
if __name__ == '__main__':fun2()
缓存和计时装饰器
【示例】实现函数执行结果缓存和计时的装饰器功能
# coding=utf-8
import time
class CacheDecorator():__cache={}def __init__(self,func):self.func = funcdef __call__(self, *args, **kwargs):# 如果缓存中有对应的方法名,则直接返回对应的返回值if self.func.__name__ in CacheDecorator.__cache:return CacheDecorator.__cache[self.func.__name__]# 如果缓存中没有对应的方法名,则进行计算,并将结果缓存else:result = self.func(*args,**kwargs)CacheDecorator.__cache[self.func.__name__] = resultreturn result
def cost_time(func):def infunc(*args,**kwargs):start = time.time()result = func(*args,**kwargs)end = time.time()print(f"耗时:{end-start}")return resultreturn infunc
@cost_time
@CacheDecorator
def func1_long_time():"""模拟耗时较长,每次执行返回结果都一样的情况"""print("start func1")time.sleep(3)print("end func1")return 999
if __name__ == '__main__':r1 = func1_long_time()r2 = func1_long_time()print(r1)print(r2)"""
运行结果:
start func1
end func1
耗时:3.0079846382141113
耗时:0.0
999
999
"""