在利用 Python 书写装饰器模式时,Python对设计模式中的装饰器模式具有天然的支持。但要确保装饰器保留被装饰函数的name和docstring时,需要使用包import functools
中的@functools.wraps
1。
使用如下代码:
# testDecorators.py
def float_args_and_return(function):
def wrapper(*args, **kwargs):
args = [float(arg) for arg in args]
return float(function(*args, **kwargs))
return wrapper
@float_args_and_return
def mean(first, second, *rest):
"""
Caculate the means
"""
numbers = (first, second) + rest
return sum(numbers) / len(numbers)
if __name__ == "__main__":
print(help(mean))
运行结果为:
可以看出,被装饰函数mean
的__name__
和docstring都没被保留。若将上述代码改为:
# testDecorators.py
import functools
def float_args_and_return(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
args = [float(arg) for arg in args]
return float(function(*args, **kwargs))
return wrapper
@float_args_and_return
def mean(first, second, *rest):
"""
Caculate the means
"""
numbers = (first, second) + rest
return sum(numbers) / len(numbers)
if __name__ == "__main__":
print(help(mean))
则运行结果为:
可以看出,使用@functools.wraps
,实现了保留被装饰函数的__name__
和docstring
功能。
Mark Summerfield. Python in Practice: Create Better Programs Using Concurrrency, Libraries, and Patterns. Addison-Wesley, 2014. ??