Python的修饰器

更多

典型应用例子

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()  

等价于下列代码,其中@timeit等价于foo = timeit(foo)

import time  

def foo():  
    print 'in foo()'  

# 定义一个计时器,传入一个,并返回另一个附加了计时功能的方法  
def timeit(func):  

    # 定义一个内嵌的包装函数,给传入的函数加上计时功能的包装  
    def wrapper():  
        start = time.clock()  
        func()  
        end =time.clock()  
        print 'used:', end - start  

    # 将包装后的函数返回  
    return wrapper  

foo = timeit(foo)  
foo()  

猜你喜欢

转载自blog.csdn.net/jason_cuijiahui/article/details/80498218