使用functools.wraps可保留被装饰函数的元信息,避免函数名、文档字符串等丢失。1. 不使用wraps时,装饰器会掩盖原函数的__name__和__doc__;2. 使用@wraps(func)后,wrapper继承原函数的元数据,确保调试和文档正确;3. 适用于日志、计时、权限等通用装饰器,提升代码可维护性。

functools.wraps 是 Python 中用于装饰器开发的一个实用工具,它的主要作用是保留被装饰函数的元信息(如函数名、文档字符串、参数列表等)。如果不使用 wraps,装饰器会“掩盖”原函数的这些信息,给调试和文档生成带来困扰。
def my_decorator(func):
def wrapper(*args, **kwargs):
print("调用前")
result = func(*args, **kwargs)
print("调用后")
return result
return wrapper
<p>@my_decorator
def say_hello():
"""打招呼函数"""
print("Hello!")</p><p>print(say_hello.<strong>name</strong>) # 输出:wrapper
print(say_hello.<strong>doc</strong>) # 输出:None</p>from functools import wraps
<p>def my_decorator(func):
@wraps(func)
def wrapper(*args, *<em>kwargs):
print("调用前")
result = func(</em>args, **kwargs)
print("调用后")
return result
return wrapper</p><p>@my_decorator
def say_hello():
"""打招呼函数"""
print("Hello!")</p><p>print(say_hello.<strong>name</strong>) # 输出:say_hello
print(say_hello.<strong>doc</strong>) # 输出:打招呼函数</p>from functools import wraps
import time
<p>def timer(func):
@wraps(func)
def wrapper(*args, *<em>kwargs):
start = time.time()
result = func(</em>args, **kwargs)
end = time.time()
print(f"{func.<strong>name</strong>} 执行耗时: {end - start:.2f}s")
return result
return wrapper</p><p>@timer
def slow_function():
time.sleep(1)</p><p>slow_function() # 输出函数名和耗时</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/xiazai/code/9569">
<img src="https://img.php.cn/upload/webcode/000/000/011/175933080587154.jpg" alt="盛世企业网站管理系统1.1.2">
</a>
<div class="aritcle_card_info">
<a href="/xiazai/code/9569">盛世企业网站管理系统1.1.2</a>
<p>免费 盛世企业网站管理系统(SnSee)系统完全免费使用,无任何功能模块使用限制,在使用过程中如遇到相关问题可以去官方论坛参与讨论。开源 系统Web代码完全开源,在您使用过程中可以根据自已实际情况加以调整或修改,完全可以满足您的需求。强大且灵活 独创的多语言功能,可以直接在后台自由设定语言版本,其语言版本不限数量,可根据自已需要进行任意设置;系统各模块可在后台自由设置及开启;强大且适用的后台管理支</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="盛世企业网站管理系统1.1.2">
<span>0</span>
</div>
</div>
<a href="/xiazai/code/9569" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="盛世企业网站管理系统1.1.2">
</a>
</div>
基本上就这些。只要写装饰器,建议都用 @wraps,避免丢失函数元信息,提升代码可维护性。不复杂但容易忽略。
以上就是python中wraps函数如何使用?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号