python - 在 Python 2.6 中不推荐使用 BaseException.message

当我使用以下用户定义的异常时,我收到一条警告说 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/

相关文章:

linux - tar.gz 和 tgz 是一回事吗?

linux - ~/.ssh/config 文件中的 SSH 端口转发?

python - 将字符串转换为 Python 类对象?

python - 通过urllib和python下载图片

python - 无法使用 Ctrl-C 终止 Python 脚本

python - 无法安装 Python 包 [SSL : TLSV1_ALERT_PROTOCOL

python - 如何让 Flask 在端口 80 上运行?

python - 将 Pandas 函数应用于列以创建多个新列?

linux - 在 bash 中检查当前分区的可用磁盘空间

linux - 从 linux shell 脚本发送邮件