zoukankan      html  css  js  c++  java
  • Python # 装饰器

    ###

    现在我有一个简单的myfunc函数,现在我想对myfunc函数增加功能。下面我们增加一个deco的功能。

    import time
    def deco(func):
        startTime = time.time()
        func()
        endTime = time.time()
        msecs = (endTime - startTime)
        print("-->elapsed time %s s"%msecs)
    
    def myfunc():
        print('start myfunc')
        time.sleep(3)
        print('end myfunc')
    
    deco(myfunc)

    但是这种方式存在一个问题,修改了myfunc的原来的调用方式:myfunc() ------> 变成了 deco(myfunc)。所以我们做了下面的改变。

    ###

    def deco(func):
        def wrapper():
            startTime = time.time()
            func()
            endTime = time.time()
            msecs = (endTime - startTime)
            print("-->elapsed time %s s"%msecs)
        return wrapper                            ###返回的是<function deco.<locals>.wrapper at 0x03234468> 可以通过wrapper()调用
    
    
    def myfunc():
    print('start myfunc')
    time.sleep(3)
    print('end myfunc')

    print("myfunc is %s"%myfunc.__name__ )
    myfunc=deco(myfunc)
    print("myfunc is %s"%myfunc.__name__ )
    myfunc()

    输出结果:

    myfunc is myfunc
    myfunc is wrapper
    start myfunc
    end myfunc
    -->elapsed time 3.0007433891296387 s

    经过了上面的改动后,一个比较完整的装饰器(deco)就实现了,装饰器没有影响原来的函数,以及函数调用的代码。

    例子中值得注意的地方是,Python中一切都是对象,函数也是,所以代码中改变了”myfunc”对应的函数对象。

    ###

    def deco(func):
        def wrapper():
            startTime = time.time()
            func()
            endTime = time.time()
            msecs = (endTime - startTime)
            print("-->elapsed time %s s"%msecs)
        return wrapper
    
    @deco
    def myfunc():
        print('start myfunc')
        time.sleep(3)
        print('end myfunc')
    
    
    myfunc()

    ###

  • 相关阅读:
    c# 利用反射设置属性值
    C#中扩展方法
    Python与Ruby比较
    Python 学习笔记(半ZZ半自己写)
    c# 写的一个类帮助器(动态生成类 动态类 动态属性)
    c#学习python
    LBS中从数据库查询某经纬度2KM范围内的数据 针对大数据量的性能优化
    隐藏ToString等系统自带方法
    C#命名规范
    SQL Server 数值四舍五入,小数点后保留2位
  • 原文地址:https://www.cnblogs.com/lwsup/p/7523582.html
Copyright © 2011-2022 走看看