在 Python 和 __init__.py 中导入模块 [英] Importing modules in Python and __init__.py
问题描述
我一直在阅读 __init__.py
文件的功能.据说我们在包含模块的文件夹中需要一个空的__init__.py
文件,这样才能导入这些模块.但是,我尝试将文件夹路径添加到 PYTHONPATH(Windows 7 中的环境变量).尽管此文件夹不包含 __init__.py
文件,但我仍然可以从该文件夹导入模块.你能解释一下如何在不存在 __init__.py
的情况下导入这些模块吗?
I have been reading about the function of __init__.py
file. It is said that we need an empty __init__.py
file in the folder which contains modules, so that these modules can be imported. However, I tried adding a folder path to PYTHONPATH (Environment Variable in Windows 7). Although this folder does not contain an __init__.py
file, I can still import the modules from that folder. Could you please explain how these modules can be imported without the existence of an __init__.py
?
谢谢,
最好的问候
推荐答案
__init__.py
将文件夹变成 包.这对于创建一种模块层次结构很有用,您可以在其中使用如下导入语句:
__init__.py
turns a folder into a package. This is useful to create a sort of hierarchy of modules, where you can have import-statements like this:
import mymodule.cool.stuff
如果没有包,这是不可能的.
This is not possible without packages.
这篇关于在 Python 和 __init__.py 中导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!