首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

关于装饰器的疑问,该如何处理

2013-01-26 
关于装饰器的疑问import time def timeit(func):def wrapper():start time.clock()func()end time.cloc

关于装饰器的疑问
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()

有参数、无参数装饰器
[解决办法]
推荐一篇文章:
http://blog.csdn.net/thy38/article/details/4471421
[解决办法]
我最近看了一篇文章还是不错的。里面可以找到系列的:
http://blog.csdn.net/beckel/article/details/3585352

热点排行