import time
# 先说一下装饰器的流程
# 首先定义一个函数
def i_can_sleep():
time.sleep(3)
start_time = time.time()
i_can_sleep()
stop_time = time.time()
print("函数运行了 %s 秒" % (stop_time-start_time))
# 函数运行了 3.0004734992980957 秒
# 如果有大量的要计算耗时的工作,每次都要编写一次,那么把重复性的东西只做一次,就需要用到装饰器
def timer(func):
def wrapper():
start_time = time.time()
func()
stop_time = time.time()
print("函数运行了 %s 秒" % (stop_time-start_time))
return wrapper
# 装饰器实现流程,让i_can_sleep接收timer的返回值
i_can_sleep = timer(i_can_sleep)
i_can_sleep()
# 函数运行了 3.000610589981079 秒 (与10-13行实现了同样的功能)
print(i_can_sleep) # <function timer.<locals>.wrapper at 0x000001E7B1EA4400>,
# 可以发现此时i_can_sleep函数即为timer函数返回的wrapper, 不那么准确的理解也可以是,这个时候的i_can_sleep已经不是本身了,而是实现着wrapper的功能,
# 然后timer(i_can_sleep)的参数传递到wrapper函数内部,最后变成了在wrapper内部调用i_can_sleep。
# 这样的写法不太优雅,慢慢就演变成了@timer的写法。
@timer
def i_can_sleep():
time.sleep(3)
i_can_sleep()
# 函数运行了 3.000610589981079 秒
##############################################
def tips(func):
def inner(a, b): # 不要忘了在这里传参数
print("start..")
func(a, b) # 不要忘了在这里接收参数
print("end..")
return inner
@tips
def add(a, b):
print(a+b)
add(3, 5)
# start..
# 8
# end..
##############################################
# 带参数的装饰器,在原有装饰器外再封装一层
def new_tips(argv):
def tips(func):
def inner(a, b):
print("start.. %s %s" % (argv, func.__name__))
func(a, b)
print("end.. ")
return inner
return tips
@new_tips('add_mod')
def add(a, b):
print(a+b)
add(3, 5)
# start.. add_mod add
# 8
# end..
############################################
# 嵌套装饰器
def decorator_out(func):
def inner():
print("外装饰器前置操作。。。。。。。。。")
func()
print("外装饰器后置操作..............")
return inner
def decorator_in(func):
def inner():
print("内装饰器前置操作。。。。。。。。。")
func()
print("内装饰器后置操作..............")
return inner
@decorator_out
@decorator_in
def destination():
print("目标函数!")
destination()
# 外装饰器前置操作。。。。。。。。。
# 内装饰器前置操作。。。。。。。。。
# 目标函数!
# 内装饰器后置操作..............
# 外装饰器后置操作..............
Python 装饰器,有新想法就继续更新。。。
猜你喜欢
转载自blog.csdn.net/xieyicn/article/details/86530844
今日推荐
周排行