装饰器的作用:

装饰器是一个通用的函数,即可能会被所有其它函数使用,为了方便被调用,通常使用装饰器进行装饰。

装饰器实际上又是一个闭包函数:函数内部定义的函数,该内部函数引用了父类函数的成员。

代码示例:定义一个可以统计函数运行时间的装饰器,可以被所有函数使用,用于统计函数运行时间。

 下面的代码中timer()为装饰器,test()函数如果想使用装饰器,在test上方添加@timer函数即可达到 func1 = timer(test)的功能。

import time

# 装饰器
def timer(func):
    print('This is dress function')
    def inner():  #闭包函数
        start = time.time()
        func()
        print(time.time()-start)
    return inner

@timer   #语法糖  等价于 func1 = timer(test)
def test():
    print('This is test function')
    time.sleep(3)

# func1 = timer(test)
# func1()

if __name__ == '__main__':
    test()
09-09 07:30