python 中装饰函数的返回值

returning values from decorated functions in python

我有以下修饰函数:

import time
def logging_time(func):
    """Decorator that logs time"""
    def logger():
        """Function that logs time"""
        start = time.time()
        func()
        print(f"Calling {func.__name__}: {time.time() - start:.5f}")

    return logger
     
@logging_time
def calculate_sum():
     return sum(range(10000))

当我 运行 calculate_sum() 我得到 Calling calculate_sum: 0.00043 这是 @logging_time.

的输出

如何同时检索 calculate_sum 函数的 return 值?为什么 sum(range(10000)) 也没有返回?

只需将结果保存在您调用函数的位置,然后 return 它

import time
def logging_time(func):
    """Decorator that logs time"""
    def logger():
        """Function that logs time"""
        start = time.time()
        result = func()  # save result here
        print(f"Calling {func.__name__}: {time.time() - start:.5f}")
        return result  # return it here

    return logger
     
@logging_time
def calculate_sum():
     return sum(range(10000))

只需存储 return 值并 return 它

import time
def logging_time(func):
    """Decorator that logs time"""
    def logger():
        """Function that logs time"""
        start = time.time()
        result = func()
        print(f"Calling {func.__name__}: {time.time() - start:.5f}")
        return result
    return logger
     
@logging_time
def calculate_sum():
     return sum(range(10000))

print(calculate_sum())

结果:

Calling calculate_sum: 0.00012
49995000