错误异常必须从BaseException派生,即使已经如此(Python 2.7)
下面这段代码有什么问题(在 Python 2.7.1 下):
class TestFailed(BaseException):
def __new__(self, m):
self.message = m
def __str__(self):
return self.message
try:
raise TestFailed('Oops')
except TestFailed as x:
print x
当我运行它的时候,我得到了:
Traceback (most recent call last):
File "x.py", line 9, in <module>
raise TestFailed('Oops')
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
但在我看来,TestFailed
确实是从 BaseException
继承而来的。
5 个回答
5
在创建类的时候,使用 __init__()
来“初始化”类,而不是 __new__()
。大多数情况下,重写 __new__
是不必要的。它是在对象创建时,先于 __init__
被调用的。
你可以查看这个链接了解更多信息:Python中 __new__ 和 __init__ 的用法?
26
其他人已经告诉你怎么修复你的代码,但我觉得有必要指出,你现在实现的行为其实已经是Python中异常的标准行为了,所以你大部分的代码其实是多余的。你只需要从Exception
(这是运行时异常的合适基类)继承,然后在里面写pass
就可以了。
class TestFailed(Exception):
pass
34
__new__ 是一个 staticmethod
,它需要返回一个实例。
相反,你应该使用 __init__ 方法:
class TestFailed(Exception):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message
try:
raise TestFailed('Oops')
except TestFailed as x:
print x