[Switch] functools.wraps defined function decorator

Transfer: https://www.cnblogs.com/fcyworld/p/6239951.html

 

  Decorator (decorator) is doing?

  For the original function by encapsulation, the decorator can be run before and after the function is executed or execute some code, respectively, which makes it possible to decorate an original function to access and modify the parameters and the return value, to achieve constraint definition, debugger, registration objective functions. Decorative generally return a wrapper (wrapper), while functools.wraps is decorative wrapper decorator.

 

First look at an example functools.wraps of the decorator:

def tracer(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print('%s(%r,%r)->%r'%(func.__name__,args,kwargs,result))
        return result
    return wrapper

@tracer
def fibonacci(n):
    if n in (0,1):
        return n
    return (fibonacci(n-1)+fibonacci(n-2))


fibonacci(3)
print(fibonacci)
print('help:')
help(fibonacci)

Output:

We can see, decorators can work properly. . .

However, the name of the function becomes a decorator in the wrapper! ! ! Built-in help function is also ineffective

In other words, the properties of the original function ineffective.

 

If you want to keep the properties of the original function, you can use the functools.wraps:

from functools import wraps
def tracer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print('%s(%r,%r)->%r'%(func.__name__,args,kwargs,result))
        return result
    return wrapper

@tracer
def fibonacci(n):
    if n in (0,1):
        return n
    return (fibonacci(n-1)+fibonacci(n-2))


fibonacci(3)
print(fibonacci)
print('help:')
help(fibonacci)

Output:

Guess you like

Origin www.cnblogs.com/leokale-zz/p/12112877.html