zoukankan      html  css  js  c++  java
  • Python学习

    1、@waps

      保证被装饰函数所有的属性保持不变

    from functools import wraps
    def wrapper(func):
        @wraps(func)
        def inner(*args,**kwargs):
            print('在被装饰的函数执行之前做的事')
            ret = func(*args,**kwargs)
            print('在被装饰的函数执行之后做的事')
            return ret
        return inner
    
    @wrapper
    def holiday(day):
        '''This is a holiday notice'''
        print('元旦放假剩余%d天'%day)
        return('好开心噻!')
    
    ret = holiday(3)
    print(ret)
    
    print(holiday.__name__)
    print(holiday.__doc__)

    2、带参数的装饰器

      常用于批量处理装饰器函数的应用与否

    import time
    flage = True
    
    def wrapper_out(flag):
        def wrapper(func):
            def inner(*args,**kwargs):
                if flag:
                    start = time.time()
                    ret = func(*args,**kwargs)
                    end = time.time()
                    print(end - start)
                    return ret
                else:
                    ret = func(*args, **kwargs)
                    return ret
            return inner
        return wrapper
    
    @wrapper_out(flage)
    def wahaha():
        time.sleep(0.1)
        print('哇哈哈!')
    @wrapper_out(flage)
    def qqxing():
        time.sleep(0.1)
        print('QQ星!')
    
    wahaha = wahaha()
    print(wahaha)
    qqxing = qqxing()
    print(qqxing)

    3、多个装饰器装饰同一个函数

      俄罗斯套娃

      

    def wrapper1(func):
        def inner(*args,**kwargs):
            print('wrapper1函数装饰被装饰函数之前的函数')
            ret = func(*args,**kwargs)
            print('wrapper1函数装饰被装饰函数之后的函数')
            return ret
        return inner
    
    def wrapper2(func):
        def inner(*args,**kwargs):
            print('wrapper2函数装饰被装饰函数之前的函数')
            ret = func(*args,**kwargs)
            print('wrapper2函数装饰被装饰函数之后的函数')
            return ret
        return inner
    
    @wrapper2
    @wrapper1
    def func():
        print('被执行的函数')
        return('小混蛋骂谁?')
    
    ret = func()
    print(ret)
  • 相关阅读:
    Java 8 CompletableFuture思考
    Math.ceil 笔记
    Python virtual env
    Reactive Stream: 如何将两个数据流接到一起,然后进行操作
    基于Apollo实现.NET Core微服务统一配置(测试环境-单机)
    在ASP.NET Core 2.x中获取客户端IP地址
    Entity Framework Core(3)-配置DbContext
    .NET Core2.1下采用EFCore比较原生IOC、AspectCore、AutoFac之间的性能
    Entity Framework Core 入门(2)
    Entity Framework Core介绍(1)
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/9381150.html
Copyright © 2011-2022 走看看