装饰器
- 器:函数
- 装饰:为其他函数添加新功能
- 装饰器:本质就是函数,功能为其他函数添加新功能
实现装饰器知识储备
高阶函数+闭包(函数嵌套)
高阶函数
- 函数接收的参数是一个函数名
- 函数的返回值是一个函数名
满足上述任意一个条件,都称为高阶函数
def foo():
print('我的函数名作为参数传给高阶函数')
def gao_jie1(func):
print('我就是高阶函数1,我接收的参数名是%s' %func)
func()
def gao_jie2(func):
print('我就是高阶函数2,我的返回值是%s' %func)
return func
gao_jie1(foo) # 将foo函数作为参数传给gao_jie1
# 我就是高阶函数1,我接收的参数名是<function foo at 0x177f30>
# 我的函数名作为参数传给高阶函数
ret=gao_jie2(foo) # 将foo函数作为参数传给gao_jie2,返回foo函数赋值给ret
print(ret)
# 我就是高阶函数2,我的返回值是<function foo at 0x177f30>
# <function foo at 0x177f30>
闭包
函数中嵌套着函数
# 闭包:在一个作用域里放入定义变量,相当于打了一个包
def father(name):
def son():
print('my father is %s' % name)
def grandson():
print('my grandfather is %s' % name)
grandson()
son()
father('aaa')
# my father is aaa
# my grandfather is aaa
装饰器使用
1.无参装饰器
wraps本身也是一个装饰器,他能把函数的元信息拷贝到装饰器函数中使得装饰器函数与原函数有一样的元信息
import time
def showtime(func):
def wrapper(a, b):
start_time = time.time()
func(a,b)
end_time = time.time()
print('spend is {}'.format(end_time - start_time))
return wrapper # 返回函数
#使用装饰器
@showtime #add = showtime(add)
def add(a, b):
print(a+b)
time.sleep(1)
#使用装饰器
@showtime #sub = showtime(sub)
def sub(a,b):
print(a-b)
time.sleep(1)
add(5,4)
# 9
# spend is 1.00523495674
sub(3,2)
# 1
# spend is 1.00521206856
2.带参装饰器
实际是对原有装饰器的一个函数的封装,并返回一个装饰器(一个含有参数的闭包函数),当使用@time_logger(3)调用的时候,Python能发现这一层封装,并将参数传递到装饰器的环境去
import time
def time_logger(flag = 0):
def showtime(func):
def wrapper(a, b):
start_time = time.time()
func(a,b)
end_time = time.time()
print('spend is {}'.format(end_time - start_time))
if flag:
print('将此操作保留至日志')
return wrapper
return showtime #返回函数
@time_logger(2) #得到闭包函数showtime,add = showtime(add)
def add(a, b):
print(a+b)
time.sleep(1)
add(3,4)
# 7
# spend is 1.0028
# 将此操作保留至日志
3.类装饰器:一般依靠类内部的__call__方法
import time
class Foo(object):
def __init__(self, func):
self._func = func
def __call__(self):
start_time = time.time()
self._func()
end_time = time.time()
print('spend is {}'.format(end_time - start_time))
@Foo #bar = Foo(bar)
def bar():
print('bar..')
time.sleep(2)
bar()
注意:不能装饰@staticmethod 或者 @classmethod已经装饰过的方法
4.常用的内置装饰器
- staticmethod: 类似实现了静态方法 注入以后,可以直接 : 类名.方法
- property:经过property装饰过的函数 不再是一个函数,而是一个property,类似实现get,set方法
本文参考:
1.https://www.cnblogs.com/whyaza/p/9505205.html
2.https://www.cnblogs.com/yujiaershao/p/10059964.html