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))
推荐阅读
- javascript - Datamap 插件不显示地图
- javascript - Formatter AxisLabel Echarts fontWeight 不起作用
- javascript - 无法使用 nuxtjs 在生产中的异步数据中获取路由参数或查询
- java - 日志中的线程轮询计数超过池大小
- laravel - 具有自动令牌更新功能的 Vue + Laravel + Gmail API
- wordpress - 如何在 Woocommerce 中自定义帐单地址的详细地址?
- java - Java Manifold 字符串模板 (manifold.systems) 中的转义美元符号 ($)
- sql - 使用 oracle 多表使用者作为流集中的来源来摄取记录
- firebase - 来自firebase firestore的flutter Horizontal singlechildscrollview
- hive - UNIONTYPE 数据连接处理