[英]Error exception must derive from BaseException even when it does (Python 2.7)
What's wrong with the following code (under Python 2.7.1):以下代码有什么问题(在 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
When I run it, I get:当我运行它时,我得到:
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
But it looks to me that TestFailed
does derive from BaseException
.但在我看来那TestFailed
确实派生自BaseException
。
__new__ is a staticmethod
that needs to return an instance. __new__是一个需要返回实例的staticmethod
。
Instead, use the __init__ method:相反,使用__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
Others have shown you how to fix your implementation, but I feel it important to point out that the behavior you are implementing is already the standard behavior of exceptions in Python so most of your code is completely unnecessary.其他人已经向您展示了如何修复您的实现,但我认为重要的是要指出您正在实现的行为已经是Python 中异常的标准行为,因此您的大部分代码完全没有必要。 Just derive from Exception
(the appropriate base class for runtime exceptions) and put pass
as the body.只需从Exception
(运行时异常的适当基类)派生,并将pass
作为主体。
class TestFailed(Exception):
pass
Use __init__()
instead of __new__()
to "initialize" classes.使用__init__()
而不是__new__()
来“初始化”类。 In most cases overriding __new__
is not necessary.在大多数情况下,不需要覆盖__new__
。 It is called before __init__
during object creation.它在对象创建期间在__init__
之前调用。
See also Python's use of __new__ and __init__?另请参阅Python 对 __new__ 和 __init__ 的使用?
The __new__
implementation should return an instance of the class, but it's currently returning None
(by default). __new__
实现应该返回类的一个实例,但它当前返回None
(默认情况下)。
However, it looks like you should be using __init__
here, rather than __new__
.但是,看起来您应该在这里使用__init__
而不是__new__
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.