def timer(f):
def inner(*args, **kwargs):
'''执行函数之前要做的'''
re = f(*args, **kwargs)
'''执行函数之后要做的'''
return re
return inner
@timer # 这是语法糖,相当于下面的 func = timer(func)
def func():
pass
# func = timer(func)
func()
from functools import wraps
def deco(func):
@wraps(func) # 加在最内层函数正上方
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@deco
def index():
'''哈哈哈哈'''
print('from index')
print(index.__doc__)
print(index.__name__)
# wraps 彻底还原到原函数index
# __doc__和__name__能够查看函数注释的方法和函数名的方法
def outer(flag):
def timer(f):
def inner(*args,**kwargs):
if flag:
print('''执行函数之前要做的''')
re = f(*args,**kwargs)
if flag:
print('''执行函数之后要做的''')
return re
return inner
return timer
def wrapper1(func):
def inner():
print('wrapper1 ,before func')
func()
print('wrapper1 ,after func')
return inner
def wrapper2(func):
def inner():
print('wrapper2 ,before func')
func()
print('wrapper2 ,after func')
return inner
@wrapper2
@wrapper1
def f():
print('in f')
f()
# wrapper2 ,before func
# wrapper1 ,before func
# in f
# wrapper1 ,after func
# wrapper2 ,after func
# f()