美文网首页
Python装饰器

Python装饰器

作者: 波波2 | 来源:发表于2021-07-15 08:04 被阅读0次

    什么是装饰器?

    类似于Java的注解。在python中叫做装饰器,目的是用于对已存在代码进行修改。这里的修改是狭义的,并非任意的修改,而是能够对其执行过程进行编译时修改。

    最简单示例

    def DecoratorTest(fun):
        def _T_fun_(id):
            print("before call -----")
            fun(id)
            print("after call -----")
        return _T_fun_
    
    @DecoratorTest
    def OutputX(id):
        print(id)
    
    OutputX(20)
    

    输出结果:

    before call -----
    20
    after call -----
    

    在没有使用装饰器之前,输出20,使用装饰器之后,实现了对OutputX函数的逻辑修改,这个就是装饰器的作用。

    有什么用?

    虽然前一个章节中,大致说明了装饰器的用法,但很多人还是不会用,原因在于不知道到底这个功能应该应用于什么场景。如果螺丝刀只是被描述为一头是一字形或十字形的器具,可能即使遇到一个螺丝,都不会想到螺丝刀,所以将工具与场景紧密关联是很重要的。装饰器常用的就两个场景:

    1. 构建流程注入,例如注入日志、性能分析处理;
    2. 程序扩展实现,适合在处理流程中添加具体扩展实现,实现类似回调功能;

    怎么用?

    流程注入

    假设一个场景:设计了一个系统,希望在某个场景下可以记录系统内函数的执行过程信息,帮助进行问题定位,实现类似日志的功能。
    简化原系统实现如下:

    def FunA(a):
      return a+20
    def FunB(a, b):
      return a+b
    def FunC(a, b):
      return FunA(a)+FunB(a, b)
    
    print(FunC(30,40))
    

    输出结果为:

    120
    

    这时,发现输出数字与预期不相符,怎么办?除了调试,如果希望通过日志来定位解决问题,那么修改系统实现如下:

    def AFun(fun):
        def CallBack(*args, **args2):
            print("befor call "+getattr(fun,"__name__"))
            ret = fun(*args, **args2)
            if ret is not None:
                print("Return:")
                print(ret)
            print("befor call "+getattr(fun,"__name__"))
            return ret
        return CallBack
            
    @AFun
    def FunA(a):
      return a+20
    @AFun
    def FunB(a, b):
      return a+b
    @AFun
    def FunC(a, b):
      return FunA(a)+FunB(a, b)
    
    print(FunC(30,40))
    

    最终输出如下:

    befor call FunC
    befor call FunA
    Return:
    50
    befor call FunA
    befor call FunB
    Return:
    70
    befor call FunB
    Return:
    120
    befor call FunC
    120
    

    通过这种方式,在不修改原代码逻辑的基础上,添加了日志执行输出功能,还可以对调用过程进行时间统计,分析系统的性能瓶颈。

    扩展实现

    假设场景:假设设计一个web框架,最起码一个需求就是用户可以扩展定义响应链接,例如响应“/a/b"的"get"请求。有两种设计方式,先看正常常规设计方式:

    url_processors = {}
    def WebEngine(url, method):
        if url in url_processors and method in url_processors[url]:
            return url_processors[url][method]()
        else:
            return 404
    
    def ProcessA():
        print("in process A")
        return "Hello A"
    
    url_processors["/A"] = {}
    url_processors["/A"]["get"] = ProcessA
    
    print(WebEngine("/A", "get"))
    print(WebEngine("/B", "get"))
    

    执行输出结果如下:

    in process A
    Hello A
    404
    

    从上边看到,修改响应信息,需要维护两个地方的代码,容易带来不一致问题,也提升了维护成本。利用装饰器如何解决这个问题,代码示例如下:

    url_processors = {}
    def WebEngine(url, method):
        global url_processors
        if url in url_processors and method in url_processors[url]:
            return url_processors[url][method]()
        else:
            return 404
    
    def DeclMethod( url="", method=""):
        def DSF(fun):
            global url_processors
            
            url_processors[url] = {}
            url_processors[url][method] = fun
        return DSF
    
    
    @DeclMethod(url="/A", method="get")
    def ProcessA():
        print("in process A")
        return "Hello A"
    
    print(WebEngine("/A", "get"))
    print(WebEngine("/B", "get"))
    

    从代码上看,扩展一个响应,只需要在函数前添加具体的扩展装饰声明即可。执行结果如下:

    in process A
    Hello A
    404
    

    总结

    在学习过程中,需要将工具与场景进行联系,在场景的解决实践中,会发现很多其他不足,例如在上例中,涉及了不定长参数的处理,装饰器参数的处理。

    相关文章

      网友评论

          本文标题:Python装饰器

          本文链接:https://www.haomeiwen.com/subject/qkbrpltx.html