描述:对于函数foo,使用修饰器修饰,在执行foo函数的同时统计执行时间。这样其他函数都可以使用此修饰器得到运行时间。

(有返回值和没有返回值的函数要用不同的修饰器似乎)

(对于有返回值的函数,不确定用result存储实际函数执行结果再最终返回的方法是不是恰当)

 import time

 def timeit(func):

     def wrapper(word):
start = time.clock()
result = func(word)
end = time.clock()
print 'Used: ', end - start
return result return wrapper @timeit
def foo(word):
return word print foo("")
 def transfer(func):
def wrapper():
result = func() result_new = {}
for key in result:
result_new[key] = result[key]
if type(result_new[key]) is type("H"):
result_new[key] = result_new[key].upper() return result_new return wrapper @transfer
def foo():
result = {}
result['name'] = "wang"
result['age'] = 1 return result print foo()

在类里

 class test:
def __init__(self):
pass def transfer(func):
def wrapper(instance):
result = func(instance)
result_new = {}
for key in result:
result_new[key] = result[key].upper() return result_new return wrapper @transfer
def getDict(self):
result = {}
result["name"] = "wang"
return result t = test()
print t.getDict()
class test:
def __init__(self):
pass def transfer(func):
def wrapper(instance):
result = func(instance)
result_new = {}
for key in result:
result_new[key] = result[key].upper() return result_new return wrapper @transfer
def getDict(self):
result = {}
result["name"] = "wang"
return result t = test()
print t.getDict()

参考文章:

http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

05-14 19:20