1.类作为装饰器
class TimeDecorator(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
start_time = time.time()
result = self.f(*args)
end_time = time.time()
print('Time elapsed for {}'.format(end_time - start_time))
return result
2.函数作为装饰器
def TimeDecorator(f):
def wrap_func(*args):
start_time = time.time()
result = f(*args)
end_time = time.time()
print('Time elapsed for {}'.format(end_time - start_time))
return result
return wrap_func
3.闭包
概念解释:一个函数定义在另一个函数作用域内,并且引用了外层函数的变量,则该函数称为闭包。
为了避免使用装饰函数后,原函数的__name__和__doc__属性变成wrap_func()函数的__name和__doc__的情况出现,python在functools包中提供了wraps()。
from functools import wraps
def TimeDecorator(f):
@wraps(f)
def wrap_func(*args):
start_time = time.time()
result = f(*args)
end_time = time.time()
print('Time elapsed for {}'.format(end_time - start_time))
return result
return wrap_func
4.带参数的装饰器
app = FlaskBrother()
@app.route('/')
def HelloWorld():
return 'hello decorator'
class FlaskBother():
def __init__(self):
self.routes = {}
def route(self,route_str):
def decorator(func):
def wrapper(*args, **kwargs):
return func(args, kwargs)
return wrapper
return decorator
def server(self,path):
view_function = self.routes.get(path)
if view_function:
return view_function()
else:
raise ValueError('Route "{}" has not been registered'.format(path))