gpt4 book ai didi

python - Python 中的 BaseException 子类问题

转载 作者:太空狗 更新时间:2023-10-29 22:07:22 33 4
gpt4 key购买 nike

我想创建自己的 Python 异常类,如下所示:

class MyException(BaseException):
def __init__(self, errno, address):
if errno == 10048:
mess = str(address) + ' is already in use'
else:
mess = 'Unable to open ' + str(address)
BaseException.__init__(mess)

但是当程序调用 BaseException.__init__() 时,我得到了这个回溯:

BaseException.__init__(mess)
TypeError: descriptor '__init__' requires a 'exceptions.BaseException' object but received a 'str'

我认为 BaseException 会接受任何一组参数。另外,我应该如何将“exceptions.BaseException”对象传递给 exceptions.BaseException 的构造函数?

最佳答案

必须以实例作为第一个参数调用基类的方法:

BaseException.__init__(self, mess)

引用自tutorial :

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments). This is occasionally useful to clients as well. (Note that this only works if the base class is defined or imported directly in the global scope.)

如 Tony Arkles 和 the documentation 中所述,

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from [Exception].

所以你不应该从 BaseException 继承,无论如何......

关于python - Python 中的 BaseException 子类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/378493/

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