关于装饰器的疑问
import time
def timeit(func):
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return wrapper
@timeit
def foo():
print 'in foo()'
foo()
这是一个很标准的装饰器 可是为什么不能这么写
import time
def timeit(func):
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
@timeit
def foo():
print 'in foo()'
foo()
第一个装饰器中嵌套的那个函数有什么作用和意义。。??
运行第二个装饰器的时候会出现错误 TypeError: 'NoneType' object is not callable 为什么会这样???
[解决办法]
import time
'''(1)无参数装饰器 '''
def timeit(func):
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return func
@timeit
def foo():
print 'in foo()'
foo()
#===================================================
''' (2)有参数装饰器 '''
print '='*60
deco_args = 'hello'
def timeit2(args):
def wrapper(foo):
start = time.clock()
foo()
end =time.clock()
print 'used:', end - start
return foo
return wrapper
@timeit2(deco_args)
def foo():
print 'Decorator with args'
foo()