简体   繁体   English

从python中的装饰函数返回值

[英]returning values from decorated functions in python

I have the following decorated function:我有以下装饰功能:

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

When I run calculate_sum() I get Calling calculate_sum: 0.00043 which is the output of the @logging_time .当我运行calculate_sum()我得到Calling calculate_sum: 0.00043这是输出@logging_time

How can I also retrieve the return value of the calculate_sum function as well ?我还如何检索calculate_sum函数的return值? Why isnt the sum(range(10000)) returned as well ?为什么sum(range(10000))返回?

Simply save result where you call the function and return it只需将结果保存在调用函数的位置并返回

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

just store the return value and return it只需存储返回值并返回它

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

Result:结果:

Calling calculate_sum: 0.00012
49995000

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

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