一个打印日志的装饰器
from functools import wraps
def log(func):
@wraps(func)
def wrapper(*args, **kwargs):
print "log: {} starting...".format(func.__name__)
result = func(*args, **kwargs)
print "log: {} ending...".format(func.__name__)
return result
return wrapper
@log
def foo():
print "foo func"
foo()
一个实用的例子
计算代码运行时间的装饰器
import time
from functools import wraps
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def countdown(n):
while n > 0:
n -= 1
countdown(100000) # countdown 0.008917808532714844
带参数的装饰器
from functools import wraps
def log(level,name=None):
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
print "[{} {}] log: {} starting...".format(level, name, func.__name__)
result = func(*args, **kwargs)
print "[{} {}] log: {} ending...".format(level, name, func.__name__)
return result
return wrapper
return decorate
@log("DEBUG", name="web_app_1")
def foo():
print "foo func"
foo()