装饰器
什么是装饰器:装饰器本质上是一个 Python 函数或类,它可以让其他函数或类在不需要做任何代码修改的前提下增加额外功能,在开发过程中防止牵一发而动全身的情况的出现。
分为类装饰器,函数装饰器。就是在类前或者函数前加上@,使用方法,调用规则一样。
作用:装饰器所做的事情就是把函数作为一个参数传入进另一个函数。
装饰器让你在一个函数的前后去执行代码。常用于日志记录,性能检测。
有了装饰器我们就可以将装饰器函数进行封装。在前面定义和装饰器同名的函数,在后面我们就可以用@装饰器名
调用这个函数。装饰器还可以极大地减少我们的冗余代码。
使用装饰器
- 函数装饰器
1.我们的业务逻辑参数中没有参数也就是
def a_function_requiring_decoration():没有参数
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
将装饰器进行封装
@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
2.类装饰器
from functools import wraps
class logit(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile
def __call__(self, func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile并写入
with open(self.logfile, 'a') as opened_file:
# 现在将日志打到指定的文件
opened_file.write(log_string + '\n')
# 现在,发送一个通知
self.notify()
return func(*args, **kwargs)
return wrapped_function
def notify(self):
# logit只打日志,不做别的
pass
@logit()
def myfunc1(x):
return x
myfunc1(4)
@logit
def myfunc2():
return 4
myfunc2()
观察两个函数的执行结果,我们可以发现结果很大区别,因为我们的return func(*args, **kwargs)一个传入参数,一个并没传入参数。因为定义的参数是*args, **kwargs所以,我们可以随意传入参数的个数。
myfunc2和myfunc2()执行结果是不同的。
3.带参数的装饰器
使用场景:
- 日志
需要注意的点
- 注意定义装饰器时候的return
- 认清装饰的本质:就是在不修改原函数的功能条件下,增加额外的功能。可以减少大量冗余代码。
functools.wraps
作用:注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。
使用方法:
调用一个wraps,在我们的装饰器中加上wrap。便可以保留传入函数的属性,保存了我们函数的名字和注释文档(docstring)。