def now():
print('2016-06-03')
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('rain:')
def now():
print('2016-06-03')
now()
像上面那样,装饰后的函数的 __name__
已经从 now
变成了 wrapper
,为什么?
is equivalent to
now
变为log('rain:')(原来的now)
Then explain why __name__ is a wrapper
According to https://docs.python.org/2.7/library/inspect.html
So
__name__
is based on the specific definition of timeLike another example
The function after decoration is actually not the now function
But log ("rain") (now)
is actually the wrapper you defined.
For this problem, there is wraps in functools that can correctly set __name__ and the like