在现代 Python 中声明自定义异常的正确方法? [英] Proper way to declare custom exceptions in modern Python?
问题描述
在现代 Python 中声明自定义异常类的正确方法是什么?我的主要目标是遵循其他异常类具有的任何标准,以便(例如)我在异常中包含的任何额外字符串都由捕获异常的任何工具打印出来.
我所说的现代 Python"是指可以在 Python 2.5 中运行但对于 Python 2.6 和 Python 3.* 的处理方式是正确的".我所说的自定义"是指一个 Exception 对象,它可以包含有关错误原因的额外数据:一个字符串,也可能是其他一些与异常相关的任意对象.
我被 Python 2.6.2 中的以下弃用警告绊倒了:
<预><代码>>>>类 MyError(异常):... def __init__(self, message):... self.message = 消息...>>>MyError("foo")_sandbox.py:3: DeprecationWarning: BaseException.message 自 Python 2.6 起已被弃用BaseException
对名为message
的属性具有特殊含义似乎很疯狂.我从 PEP-352 收集到,该属性在 2.5 中确实具有特殊含义,它们'正试图弃用,所以我猜这个名字(和那个名字)现在被禁止了?呃.
我也模糊地意识到 Exception
有一些神奇的参数 args
,但我从来不知道如何使用它.我也不确定这是未来做事的正确方式;我在网上找到的很多讨论都表明他们试图在 Python 3 中取消 args.
更新:两个答案建议覆盖 __init__
和 __str__
/__unicode__
/__repr__
.打字好像很多,有必要吗?
也许我错过了这个问题,但为什么没有:
class MyException(Exception):经过
要覆盖某些内容(或传递额外的参数),请执行以下操作:
class ValidationError(Exception):def __init__(self, message, errors):# 使用它需要的参数调用基类构造函数super().__init__(message)# 现在为您的自定义代码...self.errors = 错误
这样你就可以将错误消息的字典传递给第二个参数,然后用 e.errors
处理它.
在 Python 2 中,您必须使用这种稍微复杂的 super()
形式:
super(ValidationError, self).__init__(message)
What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.
By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.
I was tripped up by the following deprecation warning in Python 2.6.2:
>>> class MyError(Exception):
... def __init__(self, message):
... self.message = message
...
>>> MyError("foo")
_sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
It seems crazy that BaseException
has a special meaning for attributes named message
. I gather from PEP-352 that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.
I'm also fuzzily aware that Exception
has some magic parameter args
, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.
Update: two answers have suggested overriding __init__
, and __str__
/__unicode__
/__repr__
. That seems like a lot of typing, is it necessary?
Maybe I missed the question, but why not:
class MyException(Exception):
pass
To override something (or pass extra args), do this:
class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super().__init__(message)
# Now for your custom code...
self.errors = errors
That way you could pass dict of error messages to the second param, and get to it later with e.errors
.
In Python 2, you have to use this slightly more complex form of super()
:
super(ValidationError, self).__init__(message)
这篇关于在现代 Python 中声明自定义异常的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!