AttributeError: 'module' object has no attribute 'ConnectError' with Seperate Exceptions file

AttributeError: 'module' object has no attribute 'ConnectError' with Seperate Exceptions file

当我 运行 我的 python 代码

时出现错误

这是我的例外 class (exceptions.py):

#!/usr/bin/env python
class ConnectError(Exception):
    def __init__(self, arg):
        # Set some exception infomation
        self.msg = arg

这是我的连接器 class (connector.py):

#!/usr/bin/env python
import exceptions
class CardReader():
    def __init__(self):
        raise exceptions.ConnectError("ABC")

这是我的测试文件(test.py):

#!/usr/bin/env python
import connector

connect = connector()

这就是我的代码的样子,我知道我应该在我的测试文件中使用 try 和 except,但在我开始之前,我在连接器中遇到错误 class (AttributeError) .我试过使用

from exceptions import ConnectError

但这给了我一个 ImportError: cannot import name ConnectError,我试过使用这个:

from exceptions import *

然后我得到 NameError: name 'exceptions' is not defined, 然后我试了:

from exceptions import *
import exceptions

我仍然得到 AttributeError: 'module' object has no attribute 'ConnectError',我翻转了导入语句,但卡住了。我一直在网上搜索,但找不到任何有用的东西。

虽然ConnectErrorException的子类,但不在同一个模块中。所以导入 exceptions 没有你想要的效果。您需要导入声明 ConnectError 的文件。

不要raise exceptions.ConnectError。就 raise ConnectError.

我解决了我的问题,我将我的 exceptions.py 重命名为 expection.py,我不确定为什么,但我认为这个名称有影响,我使用了常规导入异常。感谢您的帮助 :D