标签:
装饰器前面提过了,采用python的闭包特性实现:
from time import time from time import sleep def count_time(): def tmp(func): def wrapped(*args, **kargs): begin_time = time() result = func(*args, **kargs) end_time = time() cost_time = end_time - begin_time print ‘%s called cost time : %s‘ %(func.__name__, cost_time) return result return wrapped return tmp @count_time() def test(): sleep(0.5) if __name__ == ‘__main__‘: test()
我们尝试以下的代码:
class Test: @count_time() def test(self): print ‘haha‘ if __name__ == ‘__main__‘: # test() a = Test() a.test()
代码仍然可以正常工作,因为a.test()仅仅就是给test添加了一个额外的参数a而已。
有些情况下,我们希望某个装饰器只用来修饰class中的方法,此时我们就需要给闭包中的函数添加一个参数self:
from time import time from time import sleep def count_time(): def tmp(func): def wrapped(self, *args, **kargs): begin_time = time() result = func(self, *args, **kargs) end_time = time() cost_time = end_time - begin_time print ‘%s called cost time : %s‘ %(func.__name__, cost_time) return result return wrapped return tmp
此时我们使用普通函数测试,结果报错:
Traceback (most recent call last): File "9.py", line 17, in <module> @count_time TypeError: count_time() takes no arguments (1 given)
标签:
原文地址:http://www.cnblogs.com/inevermore/p/4194584.html