有什么方法可以保留实际功能,即使在 python 中用装饰器结束后也是如此?

Is there any way to preserve the actual function, even after wrapping up with a decorator in python?

    @dec_sub
    def sub(a, b):
        c= a-b
        return c
    
    def dec_sub(func):
        def wrapper(a, b):
            if a<b:
                a, b = b, a
            return func(a, b)
        return wrapper
    
    print(sub(48, 9)) # first digit is bigger than the second one yields positive return
    print(sub(1, 8)) # second digit is bigger than the first one also yields positive return

#Output : 39
          7

在上面的代码中,如何在不受装饰器影响的情况下正常使用函数'sub'?

您不需要使用装饰器语法来创建装饰函数。

def sub(a, b):
    c = a - b
    return c


wrapped_sub = dec_sub(sub)

或者,您可以使用 func_tools.wraps 创建一个公开对原始函数的引用的对象。

from functools import wraps


def dec_sub(func):
    @wraps(func)
    def wrapper(a, b):
        if a<b:
            a, b = b, a
        return func(a, b)
    return wrapper

@dec_sub
def sub(a, b):
    c = a - b
    return c


sub(48, 9)   # the decorated function
sub.__wrapped__(48, 9)  # the original function