今天被Python震撼了,NB
from time import time
def logged(which):
def log(f,*args,**kargs):
print('''
'Called:
function:%s
args:%r
kargs:%r
' '''%(f,args,kargs))
def pre_logged(f):
def wrapper(*args,**kargs):
log(f,*args,**kargs)
return f(*args,**kargs)
return wrapper
def post_logged(f):
def wrapper(*args,**kargs):
now = time()
try:
return f(*args,**kargs) #会执行finally里面的语句。此处return后,post_logged其实还在执行,相当于把装饰器下面的函数加到这里了。也许我现在理解不对,姑且这么认为吧
finally:
log(f,*args,**kargs)
print('time delta:%s'%(time()-now))
return wrapper
try:
return {"pre":pre_logged,"post":post_logged}[which] #快速创建一个dict,并找到合适的函数
except (KeyError):
raise ValueError("must be 'pre' or 'post'")
@logged("post")
def hello(name):
print('Hello %s'%name)