2011-10-31 86 views
7

有什麼不對下面的代碼(Python的下2.7.1):錯誤異常,必須從即使它BaseException(Python 2.7版)獲得

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

+0

對於誰也弄不清爲什麼他們收到此錯誤的其他人:檢查,以確保你不小心做'高清MyException(例外):pass',而不是所需要的'類MyException(例外):通過'。錯過錯誤很容易。 –

回答

9

__new__是需要返回實例的靜態方法。

相反,使用__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 
+0

謝謝(和其他回答的人)。我相當懷疑這是一件簡單的事情(但我對Python本身並沒有太多的經驗)。 –

2

__new__實現應該返回類的實例,但它目前返回None(默認)。

但是,看起來你應該在這裏使用__init__,而不是__new__

11

其他人已經表明你如何解決您的實現,但我覺得它重要指出的是您正在實施的行爲已經在Python例外標準的行爲,因此大部分代碼是完全不必要的。只需從Exception(適用於運行時異常的基類)派生出來,並將pass作爲正文。

class TestFailed(Exception): 
    pass 
+0

感謝您的信息。我不知道。 (在這種情況下,這裏發佈的代碼被簡化了,我的實際'__init__'還有一些額外的參數,但我將來肯定會使用你的信息。) –

相關問題