zoukankan      html  css  js  c++  java
  • 装饰器详解

    1.装饰器案例 

    def auth(func):
        def inner(*args,**kwargs):
    
            print("执行被装饰函数前要执行的函数")
            ret =func(*args,**kwargs)
            print("执行被装饰函数前要执行的函数")
            return ret
    
        return inner
    
    @auth
    def index(*args,**kwargs):
        print("hello")
    
    index()
     
    print(index)
    print(index.__name__)

    打印结果 (装饰后 函数名发生了变化):

    执行被装饰函数前要执行的函数
    hello
    执行被装饰函数前要执行的函数
    <function auth.<locals>.inner at 0x0000023B35134840>
    inner

    装饰器步骤

    def auth(func):   # 第一步
        def inner(*args,**kwargs):  #第六步
    
            print("执行被装饰函数前要执行的函数")
            ret =func(*args,**kwargs)  #第七步
            print("执行被装饰函数前要执行的函数")
            return ret  #第九步
    
        return inner  #第三步 返回inner
    
    @auth    # index =auth(index)   #第二步 auth(index)   第四步 index =inner
    def index(*args,**kwargs):
        print("hello")    #第八步
    
    index()  #第五步
    
    print(index)
    print(index.__name__)

    给装饰器添加修复器

    functiontools.wrapper()  ,装饰器会破坏原函数的完整性 ,原函数的内置属性会跟随装饰器的第二层嵌套的函数一致,通过functiontools会还原原函数的属性的完整性.

    import  functools
    def auth(func):   # 第一步
    
        @functools.wraps(func)
        def inner(*args,**kwargs):  #第六步
    
            print("执行被装饰函数前要执行的函数")
            ret =func(*args,**kwargs)  #第七步
            print("执行被装饰函数前要执行的函数")
            return ret  #第九步
    
        return inner  #第三步 返回inner
    
    @auth    # index =auth(index)   #第二步 auth(index)   第四步 index =inner
    def index(*args,**kwargs):
        print("hello")    #第八步
    
    index()  #第五步
    
    print(index)
    print(index.__name__)

    打印结果:

    执行被装饰函数前要执行的函数
    hello
    执行被装饰函数前要执行的函数
    <function index at 0x000002657A4A4840>
    index
  • 相关阅读:
    杯具的流浪狗
    数据加密与数据压缩后加密的效率
    XMPP协议自定义消息类型扩展
    have a try
    linux修改网卡名称的方法
    WARNING: old character encoding and/or character set解决办法
    extern用法总结
    linux下的c++线程池实现
    32位linux系统操作大于2G文件方法
    eclipse中gdb调试输出stl容器的内容
  • 原文地址:https://www.cnblogs.com/mengbin0546/p/10741553.html
Copyright © 2011-2022 走看看