[英]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
。
其他人已經向您展示了如何修復您的實現,但我認為重要的是要指出您正在實現的行為已經是Python 中異常的標准行為,因此您的大部分代碼完全沒有必要。 只需從Exception
(運行時異常的適當基類)派生,並將pass
作為主體。
class TestFailed(Exception):
pass
使用__init__()
而不是__new__()
來“初始化”類。 在大多數情況下,不需要覆蓋__new__
。 它在對象創建期間在__init__
之前調用。
__new__
實現應該返回類的一個實例,但它當前返回None
(默認情況下)。
但是,看起來您應該在這里使用__init__
而不是__new__
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.