python装饰器
# 装饰器的组成 # 1.定义装饰器def time_dec() 2.获取被装饰函数(f): # 1.定义内函数def wrapper(),2,获取被装饰函数的传参(func3(1, 2, c=1)) # 1.调用函数本身,并且传参 r = f(*args, **kwargs) # 1.把装饰函数的返回值原样返回return return r # 1.调用执行函数 func3(1, 2, c=1) def time_dec(f): print(f.__name__) def wrapper(*args, **kwargs): """""" print(args) print(kwargs) # 被装饰函数之前执行 t1 = time.time() r = f(*args, **kwargs) # 被装饰函数之后执行 t2 = time.time() print(t2 - t1) return r return wrapper # 在func3上面的@time_dec,把func3这个函数本身作为time_dec函数的参数传入 # 获取调用函数的参数,在func3上面的@time_dec,把func3的参数作为time_dec的内函数wrapper的参数传入 def time2_dec(f): def wrapper(*args, **kwargs): """""" # 被装饰函数之前执行 t3 = time.time() r = f(*args, **kwargs) # 被装饰函数之后执行 t4 = time.time() print(t4 - t3) return r return wrapper
@time_dec
def func3(*args, **kwargs):
# print(args)
# print(kwargs)
z1 = 0
for n in args:
z1 += n
z2 = 0
time.sleep(3)
for key in kwargs.keys():
z2 += kwargs.get(key)
# print(z1)
# print(z2)
return z1, z2
if __name__ == '__main__':
print(func3(1, 2, c=1))
# 1.执行顺序
# 1.time_dec(f)==>返回def wrapper(*args, **kwargs):
# 2.执行def wrapper(1, 2, c=1)===>返回r
# 多重函数执行顺序
'''
第一步:time2_dec中的t3 = time.time()
第二步:time_dec中的 t1 = time.time()
第三步: r = f(*args, **kwargs)
第四步:time_dec中的 t2 = time.time()
第五步:time2_dec中的t4 = time.time()
'''
@time2_dec
@time_dec
def func3(*args, **kwargs):
# print(args)
# print(kwargs)
z1 = 0
for n in args:
z1 += n
z2 = 0
time.sleep(3)
for key in kwargs.keys():
z2 += kwargs.get(key)
# print(z1)
# print(z2)
return z1, z2