微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从python装饰函数返回值

如何解决从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输出

我还如何还检索return函数calculate_sum值?为什么sum(range(10000))也不返回?

解决方法

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

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

只需存储返回值并返回

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。