繁体   English   中英

错误异常必须从 BaseException 派生,即使它确实存在(Python 2.7)

[英]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

__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

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

class TestFailed(Exception):
    pass

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

另请参阅Python 对 __new__ 和 __init__ 的使用?

__new__实现应该返回类的一个实例,但它当前返回None (默认情况下)。

但是,看起来您应该在这里使用__init__而不是__new__

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM