栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python 2.6中不推荐使用BaseException.message

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
其他人建议的内容。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号