首页 > 解决方案 > 从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.

我怎样才能也检索函数的returncalculate_sum?为什么不sum(range(10000))退货呢?

标签: pythonpython-3.xdecoratorpython-decorators

解决方案


只需将结果保存在调用函数的位置并返回即可

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))

推荐阅读