functools wrap装饰器应用
常用场景
- 包装异常
- 打印日志
- 统计函数执行时间
下面给出一个包装异常的demo:
import functools
def wrap_exception(func):
@functools.wraps(func)
def wrapper(self,*args,**kwargs):
try:
return func(self, *args, **kwargs)
except BaseException as ex:
raise MyException(ex.message)
return wrapper
class MyException(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return self.msg
def __repr__(self):
return self.msg
class Test:
def __init__(self):
pass
@wrap_exception
def test(self):
raise Exception("Hello")
tt = Test()
tt.test()