#!/usr/bin/env python
from time import time
def logged(when):
def log(f,*arg,**kargs):
print '''Called:
funciton:%s
args:%r
kargs:%r'''%(f,arg,kargs)
def pre_logged(f):
def wrapper(*args, **kargs):
log(f,*args,**kargs)
<span style="color:#FF0000;"><em>ret=f(*args,**kargs)
return ret</em></span> #不能直接返回func的调用
return wrapper
def post_logged(f):
def wrapper(*args,**kargs):
now=time()
try:
<span style="color:#FF0000;"><em> ret=f(*args,**kargs)
return ret</em></span>
finally:
log(f,*args,**kargs)
print "time dalta:%s"%(time()-now)
return wrapper
try:
return {"pre":pre_logged,
"post":post_logged}[when]
except KeyError,e:
raise ValueError(e),'must be pre or post'
@logged("post")
def hello(name):
print "hello,",name
hello("World")
这么修改以后就可以执行了,在python2.7上通过,推荐装饰器一个比较好的文章
http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html