当我使用以下用户定义的异常时,我收到一条警告说 BaseException.message 在 Python 2.6 中已被弃用:
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
这是警告:
DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
这有什么问题?为了消除弃用警告,我需要进行哪些更改?
最佳答案
只需从 Exception
继承你的异常类,并将消息作为第一个参数传递给构造函数
例子:
class MyException(Exception):
"""My documentation"""
try:
raise MyException('my detailed description')
except MyException as my:
print my # outputs 'my detailed description'
您可以使用 str(my)
或(不太优雅)my.args[0]
来访问自定义消息。
在较新版本的 Python(从 2.6 开始)中,我们应该从 Exception 继承我们的自定义异常类(starting from Python 2.5)从 BaseException 继承。背景在PEP 352中有详细描述.
class BaseException(object):
"""Superclass representing the base of the exception hierarchy.
Provides an 'args' attribute that contains all arguments passed
to the constructor. Suggested practice, though, is that only a
single string argument be passed to the constructor."""
__str__
和 __repr__
已经以有意义的方式实现,
特别是对于只有一个 arg(可以用作消息)的情况。
您不需要重复 __str__
或 __init__
实现或创建 _get_message
其他人的建议。
https://stackoverflow.com/questions/1272138/