
保留装饰函数的签名
装饰器是 Python 中用于扩展现有函数行为的强大工具。然而,当应用于函数时,所得的修饰函数通常会丢失其原始文档和签名。这可能会出现问题,尤其是在使用执行日志记录或参数转换等常见任务的通用装饰器时。
常见解决方法
一些常见解决方法包括:
- 在装饰函数的文档字符串中包含签名。
- 为每个特定签名创建专门的装饰器。
使用装饰器模块
一个更健壮的解决方案是使用装饰器模块,它提供了一个名为@decorator.decorator的装饰器函数。通过将此装饰器应用到您自己的装饰器函数中,您可以保留原始函数的签名。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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)
@args_as_ints
def funny_function(x, y, z=3):
"" "Computes x*y + 2*z" ""
return x*y + 2*z
print (funny_function( "3" , 4.0, z= "5" )) # 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z</code>
|
登录后复制
Python 3.4
在 Python 3.4 及更高版本中, functools.wraps() 函数可用于保留签名。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <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
@args_as_ints
def funny_function(x, y, z=3):
"" "Computes x*y + 2*z" ""
return x*y + 2*z
print (funny_function( "3" , 4.0, z= "5" )) # 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z</code>
|
登录后复制
以上是如何在Python中保留修饰函数的签名?的详细内容。更多信息请关注PHP中文网其他相关文章!