有没有任何方法可以保留实际的函数,即使在用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"?

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

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

最新更新