class Exception
python 2.x 中的签名是什么?
我希望继承它并添加我自己的参数,同时正确调用super
.
以下代码有效:
class FooError(Exception):
def __init__(self, msg, x):
super(FooError, self).__init__(msg)
self.x = x
class Exception
python 2.x 中的签名是什么?
我希望继承它并添加我自己的参数,同时正确调用super
.
以下代码有效:
class FooError(Exception):
def __init__(self, msg, x):
super(FooError, self).__init__(msg)
self.x = x
你所拥有的一切都很好。交替,
class FooError(Exception):
def __init__(self, msg, x):
Exception.__init__(self, msg)
self.x = x
从文档:
派生类中的重写方法实际上可能想要扩展而不是简单地替换同名的基类方法。有一种简单的方法可以直接调用基类方法:只需调用 BaseClassName.methodname(self, arguments)。这有时对客户也很有用。(请注意,这仅在基类可作为全局范围内的 BaseClassName 访问时才有效。)
Python 文档的这一部分关于方法签名不是很明确,但有一些提示。
引用 Python 文档(6. 内置异常):
...除了提到的地方,它们都有一个“关联值”,指示错误的详细原因。这可能是包含多项信息的字符串或元组...
BaseException 声明如下:
参数
给异常构造函数的参数元组。
和例外:
在 2.5 版更改: 更改为从 BaseException 继承。
其余信息只能在来源中找到(我认为)
static int
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;
}
如您所见,它不允许关键字参数。args被初始化为new中的元组。
所以总而言之,签名将是:
def __init__ ( self, *args )
并从 Exception 继承(不限制参数)
class FooError ( Exception ):
def __init__ ( self, x, *args ):
Exception.__init__ ( self, *args )
self.x = x
我总是明确地调用基类,我不喜欢super。但这只是风格问题。
请注意,您的代码是正确的。您只需将Exception限制为仅接收一个参数,而它可以处理一个元组。
我认为__init__()
类Exception是这样的:
def __init__(self, obj):
# do something
但是我在 Python 的网站上找不到文档。这只能通过阅读 Python 的源代码来确认。