python無參裝飾器

需求:想要在test_func函數(shù)前后執(zhí)行一些代碼

1.第一部(定義函數(shù),將調(diào)用原函數(shù),使用新函數(shù)替換)

def test_func():
    return 'test_func'


def test_wrapper_func():
    print 'before'
    rt = test_func()
    print 'after'
    return rt


print test_wrapper_func()

2.第二部(原函數(shù)可以定義參數(shù))

def test_func():
    return 'test_func'


def test_wrapper_func(*args, **kwargs):
    print 'before'
    rt = test_func(*args, **kwargs)
    print 'after'
    return rt


print test_wrapper_func()

3.第三部(定義工廠函數(shù),返回wapper函數(shù))

def test_func():
    return 'test_func'


def test_wrapper_func(*args, **kwargs):
    print 'before'
    rt = test_func(*args, **kwargs)
    print 'after'
    return rt


def test_wrapper():
    return test_wrapper_func


test_wrapper_func_temp = test_wrapper()

print test_wrapper_func_temp == test_wrapper_func
print test_wrapper_func_temp()
print test_wrapper_func()

4.第四部(去掉共有的wapper函數(shù),放在工廠函數(shù)內(nèi)部)

def test_func():
    return 'test_func'


def test_wrapper():
    def wrapper(*args, **kwargs):
        print 'before'
        rt = test_func(*args, **kwargs)
        print 'after'
        return rt
    return wrapper


test_wrapper_func = test_wrapper()
print test_wrapper_func()

5.第五部(可以為所有函數(shù)添加同一功能前后執(zhí)行代碼)

def test_func()
    return 'test_func'


def test_wrapper(func):
    def wrapper(*args, **kwargs):
        print 'before'
        rt = func(*args, **kwargs)
        print 'after'
        return rt
    return wrapper


test_wrapper_func = test_wrapper(test_func)
print test_wrapper_func()

6.第6部(使用裝飾器)

def test_wrapper(func):
    def wrapper(*args, **kwargs):
        print 'before'
        rt = func(*args, **kwargs)
        print 'after'
        return rt
    return wrapper


@test_wrapper
def test_func():
    return 'test_func'


print test_func()

7.第7部(修正多個裝飾器時,使用函數(shù)fun名稱問題)

from functools import wraps

def test_wrapper(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        print 'before'
        rt = func(*args, **kwargs)
        print 'after'
        return rt
    return wrapper


@test_wrapper
def test_func():
    return 'test_func'


print test_func()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容