>>> def now():
... print '2013-12-25'
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
@log('execute')
def now():
print '2013-12-25'
运行结果:
>>> now()
execute now():
2013-12-25
3层嵌套的效果是这样的:
>>> now = log('execute')(now)
自己思考的时候想过能不能将代码改为如下:
>>> 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('hello')
... def now():
... print '2013-12-25'
结果:
>>> now()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>>
因为嵌套效果为:
>>> now = log('execute')(now)
但由于`decorator函数没有返回函数,所以
now`不能在执行调用
网友评论