gpt4 book ai didi

python - 错误异常必须从 BaseException 派生,即使它确实如此(Python 2.7)

转载 作者:IT老高 更新时间:2023-10-28 20:50:56 24 4
gpt4 key购买 nike

以下代码有什么问题(在 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 - 错误异常必须从 BaseException 派生,即使它确实如此(Python 2.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7957436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com