我的项目如下所示:
b4
\storage
__init__.py
b4_common.py
b4_mysql.py
b4_storage.py
__init__.py
b4_run.py
当我运行“python b4_run.py”时,出现错误: AttributeError:模块“b4.storage”没有属性“b4_storage”
我不是 python 专家,尤其是在名称空间处理方面,但在 Pycharm 中它看到路径很好,并会说 b4.storage.b4_storage.Storage 看起来不错。 是的,Storage类是在b4_storage.py中定义的
我遇到了一些循环引用错误,所以我直接导入所有内容,而不是“from {file} import {class}”。但是当我通过时,我遇到了这个,我不明白问题是什么。
一些历史记录:我正在尝试将 Python 2.7 项目转换为 3.12。我一路上学到了很多东西,但被困在这里了。我没有红色错误,也没有纯黄色警告。
它发生在 b4_common 中显示的第二行:
import b4.storage.b4_storage
class DatabaseStorage(b4.storage.b4_storage.Storage):
如果我将鼠标悬停在 Storage 上,PyCharm 就会明白 Storage 是 b4.storage.b4_storage 中定义的类
我很困惑,因为 b4_storage 是一个文件,而不是一个属性。
认为可能是处理“.”和“_”时出现的一些语言问题?因此,我将文件重命名为 b4_dbstorage,这样 b4.storage 和 b4_storage 之间就不会重叠,但这不是解决方案。它只是将错误更改为“AttributeError:模块'b4.storage'没有属性'b4_dbstorage'”
子文件夹被创建为 python 包而不是普通目录。
我尝试将 b4_storage.py 的内容合并到 b4_common.py 中,但现在 b4_mysql 对 b4_common.py 有同样的抱怨。
如果有帮助,输出看起来就像正在导入,直到我尝试继承存储对象。重命名该对象(以防万一它现在是一个特殊的名称)不会改变任何东西。
File "/usr/lib/python3.10/runpy.py", line 187, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File "/usr/lib/python3.10/runpy.py", line 110, in _get_module_details
__import__(pkg_name)
File "/usr/local/lib/python3.10/dist-packages/b4-0.2-py3.10.egg/b4/b4_run.py", line 25, in <module>
import b4
File "/usr/local/lib/python3.10/dist-packages/b4-0.2-py3.10.egg/b4/__init__.py", line 34, in <module>
import b4.b4_config
File "/usr/local/lib/python3.10/dist-packages/b4-0.2-py3.10.egg/b4/b4_config.py", line 33, in <module>
import b4.storage.b4_storage
File "/usr/local/lib/python3.10/dist-packages/b4-0.2-py3.10.egg/b4/storage/b4_storage.py", line 26, in <module>
import b4.storage.b4_mysql
File "/usr/local/lib/python3.10/dist-packages/b4-0.2-py3.10.egg/b4/storage/b4_mysql.py", line 26, in <module>
import b4.storage.b4_common
File "/usr/local/lib/python3.10/dist-packages/b4-0.2-py3.10.egg/b4/storage/b4_common.py", line 39, in <module>
class DatabaseStorage(b4.storage.b4_storage.Storage):
AttributeError: module 'b4.storage' has no attribute 'b4_storage'
正如@user2357112所指出的,仅仅更改为导入并没有删除循环引用,因此它仍然令人窒息地指向自己,就像衔尾蛇一样。
我能够移动引用的对象,从存储合并到公共对象,但无法将整个文件拉入。
这消除了 b4_common 中的导入 b4_storage。并且 b4_storage 不再需要导入 b4_common,只需导入主 b4 项目即可。
现在我得到“进程已完成,退出代码为 120”,但我现在可以进一步挖掘。