gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:23:32 24 4
gpt4 key购买 nike

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

关于python - 在 Python 2.6 中不推荐使用 BaseException.message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1272138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com