python------装饰器

介绍

装饰器:本质就是函数,功能是为其他函数添加附加功能
原则:
1、不修改被修改函数的源代码
2、不修改被修饰函数的调用方式

装饰器的知识储备
装饰器 = 高阶函数 + 函数嵌套 + 闭包

简单装饰器的实现

import time
#装饰器的架子
def timmer(func):# func = test
    def wrapper():        
        #print(func)
        start_time = time.time()
        func()#就是在运行test()
        stop_time = time.time()
        print("运行时间就是%s" % (stop_time - start_time))
    return wrapper

def test():
    time.sleep(3)
    print("test函数运行完毕")
    
test = timmer(test)#返回的是wrapper的地址
test()#执行的是wrapper()

语法塘

@timmer 就相当于 test = timmer(test)

import time
#装饰器的架子
def timmer(func):# func = test
    def wrapper():        
        #print(func)
        start_time = time.time()
        func()#就是在运行test()
        stop_time = time.time()
        print("运行时间就是%s" % (stop_time - start_time))
    return wrapper


@timmer
def test():
    time.sleep(3)
    print("test函数运行完毕")
    
#test = timmer(test)#返回的是wrapper的地址
test()#执行的是wrapper()

原文地址:https://www.cnblogs.com/hyxk/p/11329371.html