尝试从父文件夹导入类

发布于 2025-02-04 00:46:00 字数 1666 浏览 0 评论 0原文

因此,我正在尝试更多地了解__ INIT __。py文件的工作方式。据推测,它使您能够将字典导入包装。我使用VS代码。我的test1.py按预期运行,但是test2.py文件dosent。它给了我错误:modulenotfounderror:no模块名为“ Subdir”。我从test1.pytest2.py运行脚本。

我查找了很多资源,但是我还没有工作。在test2.2.py中,我尝试从class1.pybanana类导入Apple类。代码> class2.py (均为软件包)。 test2.py正在尝试从父目录导入,这可能是引起问题的原因,但是我该如何使其工作?

目录结构

init_file_testing/
                   test1.py
                   subdir/
                          __init__.py
                          class1.py
                          class2.py
                          subdir2/
                                  test2.py

from subdir import Apple
from subdir import Banana

a = Apple("red")
print(a)

b = Banana("yellow")
print(b)

from subdir.test_class1 import Apple
from subdir.test_class2 import Banana

test1.py

class Apple:
    def __init__(self, color):
        self.color = color
    
    def __str__(self):
        return f"The color of the apple is {self.color}"

__ init

class Banana:
    def __init__(self, color):
        self.color = color
    
    def __str__(self):
        return f"The color of the banana is {self.color}"

__。强> test2.py

import sys
sys.path.append("..")

from subdir import Apple
from subdir import Banana

a = Apple("red")
print(a)

b = Banana("yellow")
print(b)

So, I'm trying to learn a little bit more of how the __init__.py file works. It supposedly give you the ability to import a dictionaries as a package. I use VS code. My test1.py run as expected, but the test2.py file dosen't. It gives me the error: ModuleNotFoundError: No module named 'subdir'. I run the scripts from test1.py and test2.py.

I've looked up many resources, but I haven't got it too work yet. In test2.py, I try to import the Apple class from class1.py and the Banana class from class2.py (both as a package). test2.py is trying to import from a parent directory which is probably what's causing the problem, but how can I make it work?

directory structure

init_file_testing/
                   test1.py
                   subdir/
                          __init__.py
                          class1.py
                          class2.py
                          subdir2/
                                  test2.py

test1.py

from subdir import Apple
from subdir import Banana

a = Apple("red")
print(a)

b = Banana("yellow")
print(b)

__init__.py

from subdir.test_class1 import Apple
from subdir.test_class2 import Banana

class1.py

class Apple:
    def __init__(self, color):
        self.color = color
    
    def __str__(self):
        return f"The color of the apple is {self.color}"

class2.py

class Banana:
    def __init__(self, color):
        self.color = color
    
    def __str__(self):
        return f"The color of the banana is {self.color}"

test2.py

import sys
sys.path.append("..")

from subdir import Apple
from subdir import Banana

a = Apple("red")
print(a)

b = Banana("yellow")
print(b)

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

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

发布评论

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

评论(1

紫轩蝶泪 2025-02-11 00:46:01

如果您运行python test1.py并且它有效,则意味着(除非您使用其他一些技术来设置sys.path),则在INIT_FILE_TESTING中文件夹,该文件夹在搜索Python模块的路径上。如果要从Subdir Import 某物中,则需要在路径上的文件夹 - 因为这是包含subdir package的文件夹。

如果您运行python test2.py找到了文件,则意味着(类似的逻辑)您在subdir2中。用sys.path.append(“ ..”) 对路径进行黑客攻击,因为这将subdir文件夹放在路径上,但是您需要init_file_testing文件夹。相对术语,即sys.path.append(“ ../..")。


但是,如果您愿意使用相对路径作为黑客的一部分来制作这项工作,那么为什么不只是使用相对导入而不是?这就是您打算在包装中工作的方式。

看起来像:

test1.py

from .subdir import Apple, Banana

__ init __. py

from .class1 import Apple
from .class2 import Banana

test2.py

from ..subdir import Apple, Banana

然后,您只需要确保root(init_file_testing)在模块搜索路径上,无论您从哪个模块开始;并且您是从根文件夹或外部 开始的(无论如何都应该做)。确保路径设置的一种简单方法是通过在虚拟环境中安装软件包(无论如何是推荐的开发方法)。您也可以使用PythonPath环境变量来完成。

If you run python test1.py and it works, that implies (unless you used some other technique to set up the sys.path) you are in the init_file_testing folder, and that folder is on the path that is searched for Python modules. If you want to from subdir import something, then you need that folder on your path - because that is the folder that contains the subdir package.

If you run python test2.py and the file is found, that implies (similar logic) you are in subdir2. Hacking the path with sys.path.append("..") does not help, because that puts the subdir folder on the path, but you need the init_file_testing folder instead. In relative terms, that is sys.path.append("../..").


However, if you are willing to use relative paths as part of a hack to make this work, then why not just use relative imports instead? This is how you are intended to work within packages.

That looks like:

test1.py

from .subdir import Apple, Banana

__init__.py

from .class1 import Apple
from .class2 import Banana

test2.py

from ..subdir import Apple, Banana

Then, you only need to ensure that the package root (init_file_testing) is on the module search path, no matter which module you start from; and that you start from either the root folder or from outside the package folders (which you should do anyway). One easy way to ensure the path is set up is by installing your package in a virtual environment (which is the recommended approach for development anyway). You can also do it with the PYTHONPATH environment variable.

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