下面的代码(在Python2.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
。
__new__是需要返回实例的staticmethod。
相反,请使用__init__方法:
使用
__init__()
而不是__new__()
来“初始化”类。在大多数情况下,不需要重写__new__
。它在对象创建期间的__init__
之前调用。另见Python's use of __new__ and __init__?
其他人已经向您展示了如何修复您的实现,但我觉得有必要指出,您正在实现的行为已经是Python中异常的标准行为,因此您的大部分代码都是完全不必要的。只需从
Exception
(运行时异常的适当基类)派生,并将pass
作为主体。相关问题 更多 >
编程相关推荐