首页 > 其他 > 详细

2019年2月24日 装饰器基本实现

时间:2019-02-24 15:05:28      阅读:156      评论:0      收藏:0      [点我收藏+]
#装饰器框架
import time
def timer(func):
    def wrapper():
        #print(func)
        start_time=time.time()
        func()#就是在运行test()
        stop_time=time.time()
        print("stop-start=%s"%(stop_time-start_time))
    return wrapper# 这个return 是针对timer函数的


def test():
    time.sleep(2)
    print(test函数运行完毕)

test=timer(test)#返回的是wrapper的地址,然后重新对test进行赋值操作
test()#执行的是wrapper()

#@timer 语法堂?就相对于做了test=timer(test) 这个操作
#需要传装饰哪个函数,就在哪个函数上面填写@timer

》》》》》》》》》》》》》》》》》》》》》》》》

标准写法:

#装饰器框架
import time
def timer(func):
    def wrapper():
        #print(func)
        start_time=time.time()
        func()#就是在运行test()
        stop_time=time.time()
        print("stop-start=%s"%(stop_time-start_time))
    return wrapper# 这个return 是针对timer函数的


@timer
def test():
    time.sleep(2)
    print(test函数运行完毕)

def test2():
    time.sleep(3)
    print("test2函数运行完毕")

@timer
def test3():
    time.sleep(1)
    print("test3函数运行完毕")

test()
test2()
test3()

>>>

test函数运行完毕
stop-start=2.0032529830932617
test2函数运行完毕
test3函数运行完毕
stop-start=1.0023720264434814

2019年2月24日 装饰器基本实现

原文:https://www.cnblogs.com/python1988/p/10426015.html

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