一、函数的有用信息
def func():
'''
此函数的作用是拯救世界
'''
print(666)
return 666
func()
print(func.__name__) #调出函数名
print(func.__doc__) #调出注释
二、带参数的装饰器
带参数的装饰器可以让装饰器像函数一样传参
import time def timmer(*args,**kwargs): def wrapper(f): def inner(*args,**kwargs): if flag: start_time = time.time() ret = f(*args,**kwargs) time.sleep(0.3) end_time = time.time() print('此函数的执行效率%f' % (end_time-start_time)) else: ret = f(*args, **kwargs) return ret return inner return wrapper flag = True @timmer(flag,2,3) # 两步:1,timmer(flag) --> wrapper 2,@wrapper 装饰器 def func1(): print(666) @timmer(flag) def func2(): print(777) func1() func2()
三、多个装饰器装饰一个函数
def wrapper1(func): # func == f函数名
def inner1():
print('wrapper1 ,before func') # 2
func()
print('wrapper1 ,after func') # 4
return inner1
def wrapper2(func): # func == inner1
def inner2():
print('wrapper2 ,before func') # 1
func()
print('wrapper2 ,after func') # 5
return inner2
@wrapper3
@wrapper2 # f = wrapper2(f) 里面的f==inner1 外面的f == inner2
@wrapper1 # f = wrapper1(f) 里面的f==函数名f 外面的f == inner1
def f(): # 3
print('in f')
f() # inner2()