关于装点器的疑问
关于装饰器的疑问
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
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 为什么会这样???
------解决方案--------------------
- Python code
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()
------解决方案--------------------
推荐一篇文章:
http://blog.****.net/thy38/article/details/4471421
------解决方案--------------------
我最近看了一篇文章还是不错的。里面可以找到系列的:
http://blog.****.net/beckel/article/details/3585352