概念
装饰器来自 Decorator
的直译。什么叫装饰,就是装点、提供一些额外的功能。在 python 中的装饰器则是提供了一些额外的功能。
装饰器本质上是一个Python函数(其实就是闭包),它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返
回值也是一个函数对象。
装饰器用于有以下场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。
示例
def mylog(func):
def infunc():
func()
print("日志纪录")
return infunc
@mylog # 本质上等同于 fun1=mylog(fun1)
def fun1():
print("使用功能1")
@mylog # 本质上等同于 fun1=mylog(fun2)
def fun2():
print("使用功能2")
fun1()
fun2()
多个装饰器
有时候,我们需要多个装饰器修饰一个函数。比如:需要增加日志功能、增加执行效率测试功能。
装饰器函数的执行顺序是分为(被装饰函数)定义阶段和(被装饰函数)执行阶段的,装饰器函数在被装饰函数定义好后立即执行
在函数定义阶段:执行顺序是从最靠近函数的装饰器开始,自内而外的执行在函数执行阶段:执行顺序由外而内,一层层执行
示例 多个装饰器执行顺序
@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("log start")
def infunc():
print("日志记录 start")
func()
print("日志记录 end")
print("log end")
return infunc
def cost_time(func):
print("costtime start")
def infunc():
print("开始计时 start")
start=time.time()
func()
end = time.time()
print(f"结束计时 end,耗费:{end - start}")
return end-start
print("costtime 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("使用功能3")
fun2()
带参数的装饰器
def mylog(type):
def decorator(func):
def infunc(*args,**kwargs):
if type=="文件":
print("文件中:日志纪录")
else:
print("控制台:日志纪录")
return func(*args,**kwargs)
return infunc
return decorator
@mylog("文件")
def fun2(a,b):
print("使用功能2",a,b)
if __name__ == '__main__':
fun2(100,200)
内置装饰器
wraps
装饰器
一个函数不止有他的执行语句,还有着 __name__
(函数名), __doc__
(说明文档)等属性,我们之前的例子会导致这些属性改变。
functool.wraps
可以将原函数对象的指定属性赋值给包装函数对象,默认有module、name、doc
,或者通过参数选择。
# 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
property
装饰器
property
装饰器用于类中的函数,使得我们可以像访问属性一样来获取一个函数的返回值。
class User:
def __init__(self,name,month_salary):
self.name = name
self.month_salary = month_salary
@property
def year_salary(self):
return int(self.month_salary)*12
if __name__ == '__main__':
u1 = User("gaoqi","30000")
print(u1.year_salary)
staticmethod
装饰器
staticmethod
装饰器同样是用于类中的方法,这表示这个方法将会是一个静态方法,意味着该方法可以直接被调用无需实例化,但同样意
味着它没有 self
参数,也无法访问实例化后的对象。
class Person:
@staticmethod
def say_hello():
print("hello world!")
if __name__ == '__main__':
Person.say_hello()
classmethod装饰器
classmethod
这个方法是一个类方法。该方法无需实例化,没有 self
参数。相对于 staticmethod
的区别在于它会接收一个指向类本身的 cls
参数。
class Person:
@classmethod
def say_hello(cls):
print(f"我是{cls.__name__}")
print("hello world!")
if __name__ == '__main__':
Person.say_hello()
我是Person
hello world!
类装饰器
上面写的装饰器都是函数来完成的。我们用类也可以实现装饰器。类能实现装饰器的功能, 是由于当我们调用一个对象时,实际上调
用的是它的 __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()
# 缓存装饰器和计时装饰器综合练习
import time
class CacheDecorator():
__cache={}
def __init__(self,func):
self.func=func
def __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__]=result
return result
def cost_time(func):
def infunc(*args,**kwargs):
start=time.time()
result=func(*args,**kwargs)
end=time.time()
print("耗时:",end-start)
return result
return 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)