@functools.wraps(fun)
时间: 2025-01-12 11:01:37 浏览: 60
`@functools.wraps(fun)` 是 Python 标准库 functools 模块中的一个装饰器,用于保持被装饰函数的元信息(如名称、文档字符串、属性等)。当你有一个函数想要修改其行为而不改变其原始元数据时,可以使用这个装饰器。它通常用于装饰器自身,使得装饰后的函数看起来像是原函数的直接替换。
例如:
```python
import functools
def my_decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
print("Before the function call.")
result = fun(*args, **kwargs)
print("After the function call.")
return result
return wrapper
@my_decorator
def hello(name):
"""Say hello to someone."""
return f"Hello, {name}!"
hello("World") # 输出: Before the function call. Hello, World! After the function call.
```
在这个例子中,`hello` 函数实际上被 `my_decorator` 装饰了,但是 `@functools.wraps(hello)` 确保了新函数的 __name__ 和 __doc__ 属性仍指向原始函数,保持了元信息的一致性。
阅读全文
相关推荐



















