【发布时间】:2020-11-02 11:56:27
【问题描述】:
能否告诉我装饰函数是否可以保留其元数据? 这将是装饰器的代码:
def timer(func):
"""prints how long a function takes to run."""
def wrapper(*args, **kwargs):
t_start = time.time()
result = functionalists(*args, **kwargs)
t_total = time.time() - t_start
print('{} took {}s'.format(functionalists.__name__, t_total))
return result
return wrapper
以下是修饰函数。
@timer
def sleep_n_seconds(n=10):
"""pause processing for n seconds.
Args:
n (int): The number of seconds to pause for.
"""
time.sleep(n)
当我尝试使用以下代码打印文档字符串时,不会返回元数据。
print(sleep_n_seconds.__doc__)
如果我需要提供更多详细信息,请告诉我。
谢谢
【问题讨论】:
-
您在寻找
functools.wraps吗? -
参见Preserving signatures of decorated functions(python3.4+ 部分)了解 functools.wraps 的使用示例