簡體   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