Python装饰器
装饰器:用函数装饰另一个函数或类,让他们提供额外的功能(正常逻辑写在被装饰函数里,其他功能包装在装饰器里[横切功能],如一些公用功能,以实现与被代理对象业务正交),让你在一个函数的前后去执行代码。它们封装一个函数,并且用这样或者那样的方式来修改它的行为。
def a_new_decorator(a_func): def wrapTheFunction(): print("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction def a_function_requiring_decoration(): print("I am the function which needs some decoration to remove my foul smell") a_function_requiring_decoration() #outputs: "I am the function which needs some decoration to remove my foul smell" a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) #now a_function_requiring_decoration is wrapped by wrapTheFunction() a_function_requiring_decoration() #outputs:I am doing some boring work before executing a_func() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_func()
装饰器结构
from functools import wraps
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
#其他业务
result = func(*args, **kwargs)
return result
# 其他业务
return wrapper
# 装饰器自带参数 多嵌套一层
def use_logging(level):
def decorator(func):
def wrapper(*args, **kwargs):
if level == "warn":
logging.warn("%s is running" % func.__name__)
elif level == "info":
logging.info("%s is running" % func.__name__)
return func(*args)
return wrapper
return decorator
@use_logging(level="warn")
def foo(name='foo'):
print("i am %s" % name)
foo()
用类来写装饰器,类里面有__call__方法的话,函数可以像函数一样调用
from functools import wraps
class logit(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile
def __call__(self, func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile并写入
with open(self.logfile, 'a') as opened_file:
# 现在将日志打到指定的文件
opened_file.write(log_string + '\n')
# 现在,发送一个通知
self.notify()
return func(*args, **kwargs)
return wrapped_function
def notify(self):
# logit只打日志,不做别的
pass

浙公网安备 33010602011771号