python無参装飾器

2474 ワード

需要:test_でfunc関数の前後にいくつかのコードを実行します
1.第1部(関数を定義し、元の関数を呼び出し、新しい関数で置き換える)
def test_func():
    return 'test_func'


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


print test_wrapper_func()


2.第2部(元の関数はパラメータを定義できる)
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.第三部(工場関数を定義し、wapper関数を返す)
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関数を除いて工場関数の内部に置く)
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.第5部(すべての関数に同じ機能を追加できる前後実行コード)
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部(複数のデコレーションを修正する場合、関数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()