functools模块
from functools import wraps
def logged(func):
@wraps(func)
def with_logging(*args, **kwargs):
print (func.__name__() + " was called")
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
print (f.__name__) # prints 'f'
print (f.__doc__) # prints 'does some math'
def logged(func):
@wraps(func)
def with_logging(*args, **kwargs):
print (func.__name__() + " was called")
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
print (f.__name__) # prints 'f'
print (f.__doc__) # prints 'does some math'
注意functools.wraps()函数的作用:调用经过装饰的函数,相当于调用一个新函数,那查看函数参数,注释,甚至函数名的时候,就只能看到装饰器的相关信息,被包装函数的信息被丢掉了。而wraps则可以帮你转移这些信息,参见http://stackoverflow.com/questions/308999/what-does-functools-wraps-do