python 函數裝飾器

舉個例子

def a_decorator(func):
    def wrapTheFunc():
        print "before decorator"
        func()
        print "end decorator"

    return wrapTheFunc


@a_decorator
def a_func_need_decorator():
    print "In a_func_need_decorator()"


a_func_need_decorator()

輸出html

before decorator
In a_func_need_decorator()
end decorator

等價

不是很明白? python

@a_decorator bash

def a_func_need_decorator():函數

等價於spa

a_func_need_decorator = a_decorator(a_func_need_decorator)日誌

修改下代碼code

def a_decorator(func):
    def wrapTheFunc():
        print "before decorator"
        func()
        print "end decorator"

    return wrapTheFunc


def a_func_need_decorator():
    print "In a_func_need_decorator()"


a_func_need_decorator = a_decorator(a_func_need_decorator)
a_func_need_decorator()

結果是一致的htm

什麼?函數還能夠做爲對象傳輸

是的,舉例對象

def test(a):
    print a


test2 = test
test2("hello")

輸出blog

hello  

場景

帳號驗證

日誌

 

參考

https://www.runoob.com/w3cnote/python-func-decorators.html

相關文章
相關標籤/搜索