错误异常必须从BaseException派生,即使它是从BaseException派生的(Python2.7)

2024-05-16 07:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码(在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


Tags: 代码selfmessagenewreturndefasclass
3条回答

__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


Oops

使用__init__()而不是__new__()来“初始化”类。在大多数情况下,不需要重写__new__。它在对象创建期间的__init__之前调用。

另见Python's use of __new__ and __init__?

其他人已经向您展示了如何修复您的实现,但我觉得有必要指出,您正在实现的行为已经是Python中异常的标准行为,因此您的大部分代码都是完全不必要的。只需从Exception(运行时异常的适当基类)派生,并将pass作为主体。

class TestFailed(Exception):
    pass

相关问题 更多 >