zoukankan      html  css  js  c++  java
  • 装饰器1(被装饰函数不带参数)

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import time
    
    def wrapper(func):
        def deco():
            start = time.time()
            func()
            stop = time.time()
            print("the func run %s"%(stop - start))
        return deco
    
    #这里的【@wrapper】等于【test1 = wrapper(test1)】,wrapper(test1),将test1函数以实参的形式传递给wrapper函数,wrapper函数将会把deco函数的内存地址作为返回值返回给变量test1,而此时test1变量所指引的值相当于是deco函数的内存地址,如果test1()则将会执行deco函数
    @wrapper  
    def test1():
        time.sleep(3)    
        print("in the test1...")
    @wrapper
    def test2():
        time.sleep(3)    
        print("in the test2...")
    test1()
    test2()

    如果被修饰函数存在返回值呢,该怎么搞....

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import time
    
    def wrapper(func):
            def deco():
                    start = time.time()
                    a = func() #将test1函数的执行结果(返回值)赋予a变量名
                    stop = time.time()
                    print("the func run %s"%(stop - start))
                    return a
            return deco
    
    #这里的【@wrapper】等于【test1 = wrapper(test1)】,wrapper(test1),将test1函数以实参的形式传递给wrapper函数,wrapper函数将>会把deco函数的内存地址作为返回值返回给变量test1,而此时test1变量所指引的值相当于是deco函数的内存地址,如果test1()则将会执>行deco函数,
    @wrapper
    def test1():
            time.sleep(3)
            print("in the test1...")
            return ("i am fine,thank you!!!")
    
    print(test1())
    在你说话之前,先听;在你回应之前,先想;在你消费之前,先挣;在你退出之前,先试
  • 相关阅读:
    第四章 瓦解无意识
    C#操作Sqlite快速入门及相关工具收集(转)
    为什么要反应?你的惯性反应模式是什么?
    NPOI 1.2简介和教程目录
    jquery 得到当前页面高度和宽度
    第十一章 不勾招世界
    关于使用HtmlAgilityPack
    C# 网页图片采集
    互联网协议入门(转)
    对技术的态度(转)
  • 原文地址:https://www.cnblogs.com/sunweigogogo/p/7617048.html
Copyright © 2011-2022 走看看