python装饰器使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python装饰器使用相关的知识,希望对你有一定的参考价值。

说起python装饰器decorator function是个很有意思的功能,用起来很方便,关键字@

简单的理解:

是在函数执行前或后,做的一些操作,然后执行函数;然后再把函数作为赋值回来。

看下代码就理解了!

#装饰器
def before(fun):
    def tmpFunc():
        print(‘before print‘)
        fun()                          #在print之后才调用的fun函数,所以会这个装饰器会先print之后调用func
    return tmpFunc

def after(fun):
    def tmpFunc():
        fun()                          #这个呢与上边的装饰器相反,先调用了fun函数,然后才print的
        print(‘after print‘)
    return tmpFunc


@before
@after
def func():
    print ‘this is function‘

if __name__=="__main__":
    func()

  

 

以上是关于python装饰器使用的主要内容,如果未能解决你的问题,请参考以下文章

Python进阶装饰器(Decorator)

Python装饰器

python装饰器的使用

[TimLinux] Python 装饰器

python函数装饰器

python之装饰器