## 装饰器
* [参考](https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000)
>[info] #### 获取函数名称
* 函数对象有一个__name__属性,可以拿到函数的名字:
~~~
>>> now.__name__
'now'
>>> f.__name__
'now'
~~~
>[info] #### 打印日志
~~~
def log(func):
def wrapper(*args, **kw):
print 'call %s():' % func.__name__
return func(*args, **kw)
return wrapper
~~~
~~~
@log
def now():
print '2013-12-25'
~~~
~~~
>>> now()
call now():
2013-12-25
把@log放到now()函数的定义处,相当于执行了语句:
now = log(now)
~~~
>[info] 高级的日志
~~~
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('execute')
def now():
print '2013-12-25'
和两层嵌套的decorator相比,3层嵌套的效果是这样的:
>>> now = log('execute')(now)
~~~
~~~
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print '%s %s():' % (text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
~~~