我具有以下修饰功能:
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))
也不返回?
答案 0 :(得分:2)
只需将结果保存在调用函数的位置并返回
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))
答案 1 :(得分:1)
只需存储返回值并返回
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