python - 整个项目中可见的模块/类 - Python

标签 python python-3.x python-module

所以基本上我需要一个在项目的所有子目录中可见的类。该类是在 bar.py 脚本中定义的,我需要在脚本中实例化一个对象,其中 <here>标签已放置。

项目结构如下所示,程序以start_script.py开始。

base/
  start_script.py
  gui/
      __init__.py
      gui.py
      <here>
  vending/
      __init__.py
      vending.py
      <here>
  foo/
      __init__.py
      foo.py
      <here>
  bar/
      bar.py
      __init__.py

我已经尝试过相对导入,但似乎不起作用。然后我尝试了最愚蠢的解决方案,在我需要的任何地方复制所需的类,但我认为在整个项目中复制相同文件并不是一个好的做法。

我尝试的第二个解决方案是将 bar 文件夹复制到 site-packages 。它有效,但我不确定将可能仅在该项目中使用的模块复制到 site-packages 是否明智。 .

有什么建议吗?

最佳答案

(我用已编辑问题的新内容编辑了我的答案)

您的项目需要一个与 start_script.py 处于同一级别的 __init__.py 文件才能使用相对导入。

现在,您可以在例如 start_script.py 中添加您的类 SpecialSnowflake 并按如下方式使用它:

# file base/gui/gui.py
from ..start_script import SpecialSnowflake

# file base/vending/vending.py
from ..start_script import SpecialSnowflake

# file base/foo/foo.py
from ..start_script import SpecialSnowflake

这对你有用吗?

关于python - 整个项目中可见的模块/类 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823902/

相关文章:

python - Intellij/Pycharm 无法调试 Python 模块

python - 如何使用相对导入将 python 脚本拆分为多个文件?

用于处理 Excel 文件的 Python 内置模块

python - 从Google Play商店应用网站中提取评论

python - 尝试写入字典中的特定键,但它正在写入整个字典中的所有键

python-3.x - 未安装错误: TfidfVectorizer - Vocabulary wasn't fitted python

python - 在 Glade 中创建可修改的 GtkScale 对象

python - 位置参数错误: Classes and Tkinter

python - 如何解决 pywinauto 的 ElementAmbiguousError : There are 2 elements that match the criteria error

python - 监控远程FTP目录