我在 python django 应用程序中有基于类的 View 。他们中的大多数处理相同类型的异常,例如:
class A{
try:
func1()
except type1 as e:
handle1()
except type2 as e:
handle()
}
class B{
try:
func2()
func3()
except type1 as e:
handle1()
except type2 as e:
handle()
}
我想将这个异常处理保留在一个公共(public)类中(可能是一个 mixin)。哪个类需要异常处理就继承公共(public)类。
将重复的异常处理保留在公共(public)类中。我正在使用 python3 和 django1.11 - 基于类的 View
最佳答案
您可以将异常处理提取到基类并更改派生类中的实现:
In [15]: import abc
In [16]: class Base:
...: def run(self):
...: try:
...: self.do_run()
...: except:
...: print('failed')
...:
...: @abc.abstractmethod
...: def do_run(self):
...: ...
...:
In [17]: class Foo(Base):
...: def do_run(self):
...: print('run foo')
...:
In [18]: class Bar(Base):
...: def do_run(self):
...: print('fail bar')
...: raise Exception()
...:
In [19]: f = Foo()
In [20]: f.run()
run foo
In [21]: b = Bar()
In [22]: b.run()
fail bar
failed
关于python - 如何捕获像 mixin 这样的公共(public)类中的所有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52752192/