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)”的鑰匙。