[英]Why do you need to derive your custom exception from BaseException?
Every class that you create in Python implicitly derives from object
.您在 Python 中创建的每个 class 都隐式派生自
object
。 To create a new error class, you must derive it from BaseException
or one of its child classes (usually, Exception
is used for this purpose).要创建新错误 class,您必须从
BaseException
或其子类之一派生它(通常,为此目的使用Exception
)。 This custom exception will successfully pass the isinstance(MyException, object)
test, so it's still an object
.此自定义异常将成功通过
isinstance(MyException, object)
测试,因此它仍然是object
。 But I wonder, what's the reason this restraint was implemented?但我想知道,实施这种限制的原因是什么? Why do we need to derive from
BaseException
or its descendants instead of doing like this:为什么我们需要从
BaseException
或其后代派生而不是这样做:
class MyException:
pass
raise MyException()
raise
requires a few special C-level attributes to work correctly (notably these here ). raise
需要一些特殊的 C 级属性才能正常工作(尤其是这里的这些)。
The only way to get these into your object in pure python is to subclass BaseException
.在纯 python 中将这些放入 object 的唯一方法是
BaseException
。 Because of this, the python devs simply decided that every raisable object, even if defined in a C module should inherit from BaseException
to make the checks easy.正因为如此,python 开发人员简单地决定每个可提升的 object,即使在 C 模块中定义,也应该从
BaseException
继承以简化检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.