1. 两特性
1.1. 在函数调用的前后打印出日志
1.2、decorator支持
@log && @log('execute')
2. code
# -*- coding: utf-8 -*-
import functools
def log(s = None):
def decorate(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('Start')
if isinstance(s, str):
print('%s %s()' % (s, func.__name__))
else:
print('call %s()' % func.__name__)
f = func(*args, **kw)
print('Done')
return f
return wrapper
return decorate
print "==================================="
print "======== @log() ========"
print "==================================="
@log()
def now():
print('2015-3-25')
now()
print "==================================="
print "======== @log('Lanuch') ======== "
print "==================================="
@log("Lanuch ")
def now():
print('2015-3-25')
now()
print "====== print now.__name__ ====="
print now.__name__
3. Test result
4. 总结
”def log(s = None)“中的“s = None”是1.2的关键。
也是解决“TypeError: log() takes exactly 1 argument (0 given)”的钥匙。