• python中函数和方法的装饰器


    python中函数和方法的装饰器

     

    Python3.0之后加入新特性Decorators,以@为标记修饰function和class。有点类似c++的宏和java的注解。Decorators用以修饰约束function和class,分为带参数和不带参数,影响原有输出,例如类静态函数我们要表达的时候需要函数前面加上修饰@staticmethod或@classmethod,

     

    不带参数的单一使用

    In [1]:
    def spamrun(fn):
        def sayspam(*args):
            print("spam,spam,spam")
            fn(*args)
        return sayspam
    
    
    @spamrun
    def useful(a, b):
        print(a * b)
    
    
    if __name__ == "__main__":
        useful(2, 5)
    
     
    spam,spam,spam
    10
    
     

    函数useful本身应该只是打印10,可是为什么最后的结果是这样的呢,其实我们可以简单的把这个代码理解为

    In [4]:
    """
    if __name__ == "__main__":
        useful = spamrun(useful)
        useful(a, b)
    """
    
    Out[4]:
    '
    if __name__ == "__main__":
        useful = spamrun(useful)
        useful(a, b)
    '
     

    不带参数的多次使用

    In [ ]:
    def spamrun(fn):
        def sayspam(*args):
            print("spam,spam,spam")
            fn(*args)
        return sayspam
    
    
    def spamrun1(fn):
        def sayspam1(*args):
            print("spam1,spam1,spam1")
            fn(*args)
        return sayspam1
    
    @spamrun
    @spamrun
    @spamrun1
    def useful(a, b):
        print(a * b)
        
    
    if __name__ == "__main__":
        useful(2, 5)
    
     

    带参数的单次使用

    In [8]:
    def attrs(**kwds):
        def decorate(f):
            for k in kwds:
                setattr(f, k, kwds[k])
            return f
    
        return decorate
    
    
    @attrs(versionadded="2.2", author="Guido van Rossum")
    def mymethod(f):
        print(getattr(mymethod, 'versionadded', 0))
        print(getattr(mymethod, 'author', 0))
        print(f)
    
    
    if __name__ == "__main__":
        mymethod(2)
    
     
    2.2
    Guido van Rossum
    2
    
     

    实际应用:记录函数执行的时间

    In [13]:
    import time
    
    
    def timer(func):
        def wrapper(*args, **kw):
            begin_time = time.time()
            func(*args, **kw)
            end_time = time.time()
            print(f'{func.__name__} cost time:{end_time-begin_time}s')
        return wrapper
    
    
    @timer
    def test():
        time.sleep(1)
        print('test_1111')
    
    
    if __name__ == '__main__':
        test()
    
     
    test_1111
    test cost time:1.0069596767425537s
    
  • 相关阅读:
    2019-8-31-C#-标准性能测试高级用法
    2018-8-29-Roslyn-通过-Target-修改编译的文件
    2018-8-29-Roslyn-通过-Target-修改编译的文件
    2018-2-13-图论-Warshall-和Floyd-矩阵传递闭包
    2018-2-13-图论-Warshall-和Floyd-矩阵传递闭包
    2019-10-26-Inno-Setup-安装包脚本-Run-的-Flags-标记
    netfilter
    mmap内存映射
    vim替换字符串
    vim环境配置
  • 原文地址:https://www.cnblogs.com/xinmomoyan/p/15380870.html
Copyright © 2020-2023  润新知