首页 > 编程语言 > 详细

python------装饰器

时间:2019-08-10 18:49:48      阅读:87      评论:0      收藏:0      [点我收藏+]

介绍

装饰器:本质就是函数,功能是为其他函数添加附加功能
原则:
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()

python------装饰器

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!