zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    SOJ4478 Easy Problem II(模拟、栈)
    SOJ4480 Easy Problem IV (并查集)
    暴力枚举法总结
    区间DP学习总结
    51nod 1019 逆序数(逆序数+离散化)
    win7系统查看硬盘序列号步骤
    雷达图制作方法
    matlab更改打开时候默认路径
    excel多组数据散点图生成
    EndNote(三)之中文引文导入方式
  • 原文地址:https://www.cnblogs.com/xinmomoyan/p/15380870.html
Copyright © 2011-2022 走看看