#一、无参数
#!/usr/bin/env python # -*- coding:utf-8 -*- # log 函数定义 # def log(f): # def fn(x): # print 'call '+ f.__name__ +'()...'#双下划线 # return f(x) # return fn # 要让 @log 自适应任何参数定义的函数,可以利用Python的 *args 和 **kw,保证任意个数的参数总是能正常调用: def log(f): def fn(*args, **kw): print 'call ' + f.__name__ + '()...' return f(*args, **kw) return fn @log def factorial(n): return reduce(lambda x,y:x*y,range(1,n+1)) print factorial(10) @log def add(x,y): return x+y print add(2,4) #请编写一个@performance,它可以打印出函数调用的时间。 import time def performance(f): def fn(*args,**kwargs): print 'call '+f.__name__+'()... at '+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) return f(*args,**kwargs) return fn @performance def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10) #二、带参数 #!/usr/bin/env python # -*- coding:utf-8 -*- #python中编写带参数decorator import time import functools def performance(unit): def perf_decorator(f): @functools.wraps(f) def wrapper(*args, **kw): t1 = time.time() r = f(*args, **kw) t2 = time.time() t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1) print 'call %s() in %f %s' % (f.__name__, t, unit) return r return wrapper return perf_decorator @performance('ms') def factorial(n): return reduce(lambda x,y: x*y, range(1, n+1)) print factorial(10) print factorial.__name__