当我使用以下用户定义的异常时,我收到一条警告,指出 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
并将消息作为第一个参数传递给构造函数
Example:
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 继承自定义异常类(从Python 2.5开始 http://docs.python.org/library/exceptions.html#exceptions.Exception) 继承自 BaseException。背景详细描述在PEP 352 http://www.python.org/dev/peps/pep-0352/.
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__
and __repr__
已经以有意义的方式实施,
特别是对于只有一个参数(可以用作消息)的情况。
您无需重复__str__
or __init__
实施或创建_get_message
正如其他人所建议的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)