首页  >  文章  >  后端开发  >  如何使用 Python 装饰器保留函数签名?

如何使用 Python 装饰器保留函数签名?

Barbara Streisand
Barbara Streisand原创
2024-10-17 17:00:03873浏览

How to Preserve Function Signatures with Python Decorators?

使用装饰器保留函数签名

装饰器是 Python 中的强大工具,但它们也会引入装饰函数签名的问题。要保留原始函数的签名,请考虑以下方法:

方法 1:装饰器模块

安装装饰器模块(pip installdecorator)并调整您的装饰器以使用其 @decorator.decorator 语法:

<code class="python">import decorator

@decorator.decorator
def args_as_ints(f, *args, **kwargs):
    args = [int(x) for x in args]
    kwargs = dict((k, int(v)) for k, v in kwargs.items())
    return f(*args, **kwargs)</code>

方法 2:functools.wraps() (Python 3.4 )

Python 3.4 引入了 functools.wraps(),其中保留函数签名:

<code class="python">import functools

def args_as_ints(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args = [int(x) for x in args]
        kwargs = dict((k, int(v)) for k, v in kwargs.items())
        return func(*args, **kwargs)
    return wrapper</code>

两种方法都可以有效地保留修饰后的函数签名。此外,functools.wraps() 可用于与旧版 Python 兼容。

以上是如何使用 Python 装饰器保留函数签名?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn