Python functools - zhongjiajie/zhongjiajie.github.com GitHub Wiki
python内置的装饰器,主要用于修饰装饰器,将原函数的元信息拷贝到装饰器里面的函数中,保证装饰器功能不会影响原函数的功能,例如有些依赖函数签名的代码执行就会出错
# 没有用 functools.wraps 之前
def logged(func):
def with_logging(*args, **kwargs):
print(func.__name__) # 输出 'with_logging'
print(func.__doc__) # 输出 None
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
f(2)
# with_logging
# None
# 6
# 使用 functools.wraps 将原函数元数据复制到装饰器的函数
from functools import wraps
def logged(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__) # 输出 'f'
print(func.__doc__) # 输出 'does some math'
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
f(2)
# f
# does some math
# 6