美文网首页
python装饰器

python装饰器

作者: Evtion | 来源:发表于2017-09-02 22:31 被阅读0次

    最近在学习python3,对于python的装饰器,多线程以及异步IO有点卡顿。这两天在研究python的装饰器,之前在看廖雪峰大神的装饰器感觉一脸懵逼。转而去看伯乐在线的装饰器教程,这里不是做广告。伯乐在线的确解决挺多疑惑。仔细阅读了很多作者的装饰器教程,特此做个总结来加深对python的装饰器的了解。

    1.函数
    • 在python当中函数也是可以直接作为函数参数传给另外一个函数。在这种情况,函数也是作为一个变量,例如:
    def now(func):
      func()
    def hello():
      print("hello world")
    now(hello)
    #直接输出 hello world
    
    2. 作用域
    • python函数内部定义变量,我们称为局部变量,有人称为命名空间。python作用域与javascript的作用域相似。函数内部定义的变量,函数外不能直接访问(全局作用域下);如果全局作用域下与函数作用域存在同名变量,函数会优先使用函数内部变量值;若函数内部不存在这个变量,则解释器会一层层往上访问直至全局作用域(如果不存在,则抛出错误)。
    1. def func():
        name="kiwis"
        print("my name is %s"%name)
       func()
    # python shell环境1输出 my name is kiwis
    
    2. 
    name ="DB"
    def func():
      name="kiwis"
      print("my name is %s"%name)
    func()
    # python shell环境1输出 my name is kiwis
    
    3. 
    name ="DB"
    def func():
      print("my name is %s"%name)
    func()
    # python shell环境1输出 my name is DB
    
    3.装饰器
    • 装饰器到底是什么?为什么要使用装饰器?装饰器顾名思义就是锦上添花,装饰,为原有事物添加更好的东西。如果我们在初期定义了一个函数;但是突然之间想要知道这个函数执行了多长时间;但是又不用修改原有函数,这个时候python装饰器派上用场。示例如下:
    from datetime import datetime
    def logtime(func): 
      def runFun(*args,**kwargs):
        print("the start time is %s"%datetime.now())
        res=func(*args, **kwargs)
        print("the end time is %s"% datetime.now())
        return res
      return runFun()
    def add():
      print("hello world")
    add=logtime(add())
    
    • 上面add=logtime(add())在python中提供了用@标识符来表示装饰器的语法糖,用@表示的语法其实和上面最后一句作用是一样的。示例代码如下:
    from datetime import datetime
    def logtime(func): 
      def runFun(*args,**kwargs):
        print("the start time is %s"%datetime.now())
        res=func(*args, **kwargs)
        print("the end time is %s"% datetime.now())
        return res
      return runFun()
    @logtime
    def add():
      print("hello world")
    
    • 在使用python装饰器时,装饰器函数返回一个函数runFun,此时add函数的name值已经不是add了,如果要改变成原来的相关变量,python中提供了functools.wrap()帮助我们完成。
    from datetime import datetime
    def logtime(func): 
      @functools.wrap(func)
      def runFun(*args,**kwargs):
        print("the start time is %s"%datetime.now())
        res=func(*args, **kwargs)
        print("the end time is %s"% datetime.now())
        return res
      return runFun()
    @logtime
    def add():
      print("hello world")
    

    python装饰器有针对函数的装饰器和对象的装饰器。下次继续阐述一下面对对象的装饰器。

    相关文章

      网友评论

          本文标题:python装饰器

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