简体   繁体   English

python 装饰器不返回 function 值

[英]python decorator not returning function value

I'm starting with decorators so I tried a basic example a debug decorator where it prints function name, input arguments and output value.我从装饰器开始,所以我尝试了一个调试装饰器的基本示例,它打印 function 名称,输入 arguments 和 output 值。 The below is my debug decorator.下面是我的调试装饰器。

def debug(func):
    @functools.wraps(func)
    def wrapper_debug(*args, **kwargs):
        args_repr = [repr(a) for a in args]                     
        kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]  
        signature = ", ".join(args_repr + kwargs_repr)           
        print(f"Calling {func.__name__}({signature})")
        value = func(*args, **kwargs)
        print(f"{func.__name__!r} returned {value!r}")           
        return value
    return wrapper_debug

Getting the factorial of each number and at the end sum of all these factorials I wanted.获取每个数字的阶乘以及我想要的所有这些阶乘的最终总和。 Unable to get the sum of factorials.无法得到阶乘的总和。 ie the debug decorator is not returning the original function value.即调试装饰器没有返回原始的 function 值。

from decorator import debug
import math

math.factorial = debug(math.factorial)

def approximate_e(terms=18):
    return sum(1 / math.factorial(n) for n in range(terms))

approximate_e(5)

This is the output I'm getting when I run the code这是我运行代码时得到的 output

Calling factorial(0)
'factorial' returned 1
Calling factorial(1)
'factorial' returned 1
Calling factorial(2)
'factorial' returned 2
Calling factorial(3)
'factorial' returned 6
Calling factorial(4)
'factorial' returned 24

Expected output:预期 output:

Calling factorial(0)
'factorial' returned 1
Calling factorial(1)
'factorial' returned 1
Calling factorial(2)
'factorial' returned 2
Calling factorial(3)
'factorial' returned 6
Calling factorial(4)
'factorial' returned 24
2.708333333333333

It does return the value, but you don't print it after the call...确实返回了值,但您在调用后不打印它......

Do this:做这个:

print(approximate_e(5))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM