我有多个函数调用需要抛出相同的异常,我已经为此任务创建了一个装饰器,以便不重复异常处理代码,但我想让这个装饰器通用,以便处理由用户。 我在下面附上了我的示例代码。
def exception_decorator(func):
def new_func(*args, **kwargs):
try:
ret = func(*args, **kwargs)
return ret
except OSError as e1:
return str(e1)
except ZeroDivisionError as e2:
return str(e2)
except ImportError as e3:
return str(e3)
except IOError as e4:
return str(e4)
except NameError as e5:
return str(e5)
return new_func
class Foo:
def __init__(self):
pass
@exception_decorator
def func1(self):
return 1/0
@exception_decorator
def func2(self):
f = open("filename","r")
return "done"
@exception_decorator
def func3(self):
return datetime.datetime.now()
obj = Foo()
print obj.func2()
我已经在装饰器中硬编码了异常列表,我希望在应用装饰器时传递异常列表并实现相同的行为。任何关于如何实现这一点的想法。 另外,我如何使这个装饰器成为一个类函数,而不是在类之外定义它? 预先感谢您的帮助。
最佳答案
您可以使用一个包装函数,该函数接受异常的可变参数并返回一个装饰器:
def exception_decorator(*exceptions):
def decorator(func):
def new_func(*args, **kwargs):
try:
ret = func(*args, **kwargs)
return ret
except exceptions as e:
return str(e)
return new_func
return decorator
这样:
import datetime
class Foo:
def __init__(self):
pass
@exception_decorator(ZeroDivisionError)
def func1(self):
return 1/0
@exception_decorator(IOError, OSError)
def func2(self):
f = open("filename","r")
return "done"
@exception_decorator(TypeError, ValueError)
def func3(self):
return datetime.datetime.strptime('2018/13/06', '%Y/%m/%d')
obj = Foo()
print obj.func1()
print obj.func2()
print obj.func3()
输出:
integer division or modulo by zero
[Errno 2] No such file or directory: 'filename'
time data '2018/13/06' does not match format '%Y/%m/%d'
关于python - python中多个函数的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53183642/