从父级的子文件夹导入Python [英] Python importing from parent's child folder

查看:43
本文介绍了从父级的子文件夹导入Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.我有这样的目录设置:

I have a question. I have a directory setup like this:

folder/
       main.py
       /stuff/
             __init__.py
             function.py
       /items/
             __init__.py
             class.py

我的问题是如何将class.py导入到function.py中?此设置非常具体,无法更改.我需要投入什么才能使其正常工作?

My question is how would I import the class.py into the function.py? This setup is very specific and is unable to be changed. What would I need to put in order for this to work?

推荐答案

只要通过 main.py 启动应用程序,您当前的目录结构似乎是理想的.

Your current directory structure seems ideal, so long as the application is started via main.py.

Python始终会自动将主脚本的父目录添加到 sys.path 的开头(即示例中的 folder ).这意味着在搜索不属于标准库的模块和软件包时,导入机制将赋予该目录优先级.

Python will always automatically add the parent directory of the main script to the start of sys.path (i.e. folder in your example). This means that the import machinery will give that directory priority when searching for modules and packages that are not part of the standard libarary.

鉴于此,您可以将 classes.py 模块导入到 function.py 中,如下所示:

Given this, you can import the classes.py module into function.py, like so:

from items import classes

(请注意,我已经重命名了该模块,因为 class 是python关键字).

(Note that I have renamed the module, because class is a python keyword).

如果您以后在 stuff 中添加了另一个模块,并想将其导入到 functions.py 中,则可以执行以下操作:

If you later added another module to stuff, and wanted to import it into functions.py, you would do:

from stuff import another

,如果将子包添加到 items ,并且您想要从中导入模块,则可以执行以下操作:

and if a sub-package was added to items, and you wanted to import a module from that, you would do:

from items.subpackage import module

可以从应用程序中的 any 模块使用以这种自上而下的方式指定的导入,因为它们始终相对于主脚本的父目录具有优先级.

Imports specified in this top-down way can be used from any module within the application, because they are always relative to the parent directory of the main script, which has priority.

这篇关于从父级的子文件夹导入Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆