python Exceptions中意外的参数处理

use*_*028 2 python exception-handling

在创建自定义Exception类时,我遇到了基本Exception类处理参数的意外情况.具体来说,它是如何设置'message'属性的.

当您将多个参数传递给它时Exception.__init__(),它不会初始化消息属性.例如,这是有效的

>>> e = Exception('msg')
>>> e.message
'msg'
Run Code Online (Sandbox Code Playgroud)

但这不会设置消息属性

>>> e = Exception('msg', 'extra')
>>> e.message
''
Run Code Online (Sandbox Code Playgroud)

它当然会存储args属性中的所有参数:

>>> e = Exception('msg', 'extra')
>>> e.args
('msg', 'extra')
Run Code Online (Sandbox Code Playgroud)

任何人都可以阐明这一点吗?我已经浏览了Exception文档,但是我很难理解为什么Exception类会这样做.如果重要,这是python 2.7

wim*_*wim 5

使用来源,卢克!

BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
{
    if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
        return -1;

    Py_DECREF(self->args);
    self->args = args;
    Py_INCREF(self->args);

    if (PyTuple_GET_SIZE(self->args) == 1) {
        Py_CLEAR(self->message);
        self->message = PyTuple_GET_ITEM(self->args, 0);
        Py_INCREF(self->message);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

因此,仅当args为长度1时才设置消息.

此行为的原因是为了向后兼容. Exception.message弃用因为Python 2.6,并为实施BaseException.__str__并不在消息看-它仅使用ARGS元组.