zoukankan      html  css  js  c++  java
  • Python 中的装饰器

    装饰器的作用:

      使用装饰器模式进行代码设计的好处在于,我可以对原来的功能不进行修改,只需要重新写一个新函数对原来的功能进行封装,增加代码的可复用性。

    Python中的装饰器:

      Python中实现装饰器是十分容易的,因为所有的方法在Python中都被视为一个变量,函数可以进行参数性的传递。接下来通过一个例子来实现Python中的装饰器的使用

      我想实现一个基本的功能,即:得到 this is somebody home page的语句

      def my_view(name):

        return "this is %s home page" %s name
      print my_view("my") #this is my home page
      1)装饰器的基本用法:
        我想利用HTML标签语言对这句话进行修改,令它能够在前台界面上加粗,那么只要:
        def bold(func):
          def wapper(*args, **kwargs):
            return "{tag_prefix}{content}{tag_suffix}".format(tag_prefix="<b>",content=func(*args, **kwargs),tag_suffix="</b>")
        
        @bold
        def my_view(name):
          return "this is %s home page" %s
        print my_view(name) #<b>this is my home page</b>
     
     
        简要分析一下以上代码,@bold在Python中会被解释为:bold(my_view),就是将my_view函数当做一个函数参数传入了bold方法中,并且,在bold方法中,定义了一个wapper函数,在这个方法中,将my_view函数的返回值进行装饰放入到wapper函数的返回值中,从而达到了装饰器的作用。
      2)带参数的装饰器:
        如果,我想要有一个更有意思的功能,我想给这句话加上任意的标签,比如说<h1>或者是<p>,具体代码如下: 
        def tag_decorate(tag_prefix_str, tag_suffix_str):#这个是使用装饰器时的参数
          def tag(func)#获得函数
            def warpper(*func_args, **func_kargs):被装饰函数的参数列表
              return "{tag_prefix}{content}{tag_suffix}".format(tag_prefix=tag_prefix_str,content=func(*args, **kwargs),tag_suffix=tag_suffix_str)
          return func
        
        @tag_decorate("<h1>", "</h2>)
        def my_view(name):
          return "this is %s home page" %s
        
        print my_view("my")#<h1>this is my home page</h1>
        简要分析一下以上的代码,在tag_decorate函数中,定义了了tag函数,在tag函数和上面一样。在tag_decorate函数中能够获得到<h1>和</h1>这个参数,而tag函数也是获得到了my_view这个函数
  • 相关阅读:
    CodeForces 659F Polycarp and Hay
    CodeForces 713C Sonya and Problem Wihtout a Legend
    CodeForces 712D Memory and Scores
    CodeForces 689E Mike and Geometry Problem
    CodeForces 675D Tree Construction
    CodeForces 671A Recycling Bottles
    CodeForces 667C Reberland Linguistics
    CodeForces 672D Robin Hood
    CodeForces 675E Trains and Statistic
    CodeForces 676D Theseus and labyrinth
  • 原文地址:https://www.cnblogs.com/Rubick7/p/6475038.html
Copyright © 2011-2022 走看看