python decorator in @wraps

python decorator in @wraps

First piece of code: no added @wraps

def user_login_confirm(name):
    print('我是', name)
    def deco_fun(view_func):
        print('准备变身。。。')
        def wrapper():
            view_func()
            print('变身完成。。。')
        return wrapper
    return deco_fun

@user_login_confirm('小辣椒')
def tony():
    print('我是', tony.__name__)

tony()

operation result:

我是 小辣椒
准备变身。。。
我是 wrapper
变身完成。。。

The second paragraph of code: one more function tony

def user_login_confirm(name):
    print('我是', name)
    def deco_fun(view_func):
        print('准备变身。。。')
        def wrapper():
            view_func()
            print('变身完成。。。')
        return wrapper
    return deco_fun

@user_login_confirm('小辣椒')
def tony():
    print('我是', tony.__name__)

def tony():
    print('我是', tony.__name__)

tony()

operation result:

我是 小辣椒
准备变身。。。
我是 tony

The third paragraph of code: add @wraps

from functools import wraps

def user_login_confirm(name):
    print('我是', name)
    def deco_fun(view_func):
        print('准备变身。。。')
        @wraps(view_func)
        def wrapper():
            view_func()
            print('变身完成。。。')
        return wrapper
    return deco_fun

@user_login_confirm('小辣椒')
def tony():
    print('我是', tony.__name__)

tony()

Conclusion: The
decoration will be decorated function becomes a wrapper function, even function name has changed, allowing the function name change back by @wraps (func).

Guess you like

Origin blog.51cto.com/14265713/2425267