在Python中,可以使用functools
模块中的wraps
装饰器来保留简单装饰器中的方法签名。wraps
装饰器可以将被装饰的函数的元数据复制到包装函数中,包括函数名、参数列表、docstring等。
下面是一个示例代码,展示了如何使用wraps
装饰器保留方法签名:
from functools import wraps
def simple_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# 在装饰器中的一些额外操作
print("Do something before the decorated function")
# 调用原始函数
result = func(*args, **kwargs)
# 在装饰器中的一些额外操作
print("Do something after the decorated function")
return result
return wrapper
@simple_decorator
def my_function(arg1, arg2):
"""这是一个被装饰的函数"""
print("Hello from my_function")
return arg1 + arg2
# 使用被装饰的函数
result = my_function(1, 2)
print(result)
print(my_function.__name__) # 输出: my_function
print(my_function.__doc__) # 输出: 这是一个被装饰的函数
在上面的示例中,simple_decorator
是一个简单的装饰器,它包装了一个被装饰的函数my_function
。使用@wraps(func)
装饰器将wrapper
函数的元数据设置为与func
函数相同,这样my_function
的名称和docstring将保留不变。
运行上面的示例代码,将会输出以下结果:
Do something before the decorated function
Hello from my_function
Do something after the decorated function
3
my_function
这是一个被装饰的函数
可以看到,my_function
的方法签名和docstring都被保留下来了。