Infrorror:如何从父目录导入功能或类

发布于 2025-02-13 15:16:26 字数 488 浏览 2 评论 0原文

我正在尝试将类从父目录导入到我的脚本中,但是我接收未知的父母软件包错误的尝试相对导入,我已经在Internet中到处搜索,但仍然无法解决错误。这是我的软件包结构:

A/
  a.py
  __init__.py
  B/
    __init__.py
    c.py

现在假设我有 class1 内部a.py模块,我正在尝试在c.py模块中导入它。 。我已经尝试过:

from ..A.a import class1

但是我收到了上述错误消息,我尝试将一个文件夹添加到sys.path ,但仍然存在相同的错误。任何人都可以解释如何从函数或类导入parent Directory到子目录的软件包(例如a.py c.py

I am trying to import a class from parent directory to my script but I receive attempted relative import with no known parent packageerror, I have searched everywhere in the internet but still cannot fix the error. Here is my package structure:

A/
  a.py
  __init__.py
  B/
    __init__.py
    c.py

Now assume I have class1 inside a.py module and I am trying to import it in the c.py module. I have tried:

from ..A.a import class1

But i get above error message I have tried to add the A folder to sys.path but still the same error. Can anyone explain how I can import a package from a function or class from parent directory to subdirectory (like from a.py to c.py)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海夕 2025-02-20 15:16:26

我这样做的方式是通过附加来扩展c.py文件中的路径。以下是一个示例:

a.py (expent the parent Directory中的示例模块)

class class1:
    def __init__(self):
        print("This worked!")

文件中的a.py在父目录中)

# By importing the sys module, you can change many
# things including the system environment.
import sys
sys.path.append("../")

# Once you've added the parent directory, you can freely
# import as you would have normally.
from a import class1
instance = class1() 

c.py (示例 您的..无效的是,以开头的导入。它)。使用您的示例的一个示例是将d.pya.py一起添加,该可以从a.py通过使用.d Import *使用

The way I do this is my extending the path in the c.py file by appending it. Below is an example of this:

a.py (example module in the parent directory)

class class1:
    def __init__(self):
        print("This worked!")

c.py (example file invoking a.py in the parent directory)

# By importing the sys module, you can change many
# things including the system environment.
import sys
sys.path.append("../")

# Once you've added the parent directory, you can freely
# import as you would have normally.
from a import class1
instance = class1() 

The reason why your .. didn't work is because imports starting with . or .. are for importing from within things being imported (the way I understand it). An example of this to use your example would be to add a d.py alongside a.py which could be imported from a.py by using from .d import *.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文