您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python 2.6中不推荐使用BaseException.message

Python 2.6中不推荐使用BaseException.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继承自定义异常类,而Exception(从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 2022/1/1 18:49:47 有389人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶