[英]Error exception must derive from BaseException even when it does (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
。
其他人已经向您展示了如何修复您的实现,但我认为重要的是要指出您正在实现的行为已经是Python 中异常的标准行为,因此您的大部分代码完全没有必要。 只需从Exception
(运行时异常的适当基类)派生,并将pass
作为主体。
class TestFailed(Exception):
pass
使用__init__()
而不是__new__()
来“初始化”类。 在大多数情况下,不需要覆盖__new__
。 它在对象创建期间在__init__
之前调用。
__new__
实现应该返回类的一个实例,但它当前返回None
(默认情况下)。
但是,看起来您应该在这里使用__init__
而不是__new__
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.